bluelamp 6.6.26 → 6.6.27
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.
- package/dist/auth/InteractiveLogin.js +1 -1
- package/dist/auth/PortalAuthClient.js +1 -1
- package/dist/auth/TokenManager.js +1 -1
- package/dist/bin/bluelamp-vscode-base.mjs +1 -1
- package/dist/i18n/en.d.ts +31 -6
- package/dist/i18n/en.d.ts.map +1 -1
- package/dist/i18n/en.js +1 -1
- package/dist/i18n/en.js.map +1 -1
- package/dist/i18n/ja.d.ts +31 -6
- package/dist/i18n/ja.d.ts.map +1 -1
- package/dist/i18n/ja.js +1 -1
- package/dist/i18n/ja.js.map +1 -1
- package/dist/lib/claudeExitDiagnosis.d.ts +94 -0
- package/dist/lib/claudeExitDiagnosis.d.ts.map +1 -0
- package/dist/lib/claudeExitDiagnosis.js +1 -0
- package/dist/lib/claudeExitDiagnosis.js.map +1 -0
- package/dist/lib/mcp-server/index.cjs +1 -1
- package/dist/lib/mcp-server/portal-api-client.cjs +1 -1
- package/dist/lib/transcriptFree.d.ts +20 -7
- package/dist/lib/transcriptFree.d.ts.map +1 -1
- package/dist/lib/transcriptFree.js +1 -1
- package/dist/lib/transcriptFree.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
const{Server:Server}=require("@modelcontextprotocol/sdk/server/index.js"),{StdioServerTransport:StdioServerTransport}=require("@modelcontextprotocol/sdk/server/stdio.js"),{CallToolRequestSchema:CallToolRequestSchema,ListToolsRequestSchema:ListToolsRequestSchema}=require("@modelcontextprotocol/sdk/types.js"),{getPromptFromPortal:getPromptFromPortal,listAvailableMcps:listAvailableMcps,downloadMcpPackage:downloadMcpPackage,getGatewayConfig:getGatewayConfig,searchMcpServices:searchMcpServices,installMcpService:installMcpService,setServiceDeactivated:setServiceDeactivated,uninstallMcpService:uninstallMcpService,updateMcpEnv:updateMcpEnv,callMcpToolProxy:callMcpToolProxy}=require("./portal-api-client.cjs"),{requireFromPackage:requireFromPackage}=require("../requireFromPackage.cjs"),{logger:logger}=requireFromPackage(require,"../../utils/logger"),{t:t,setLanguage:setLanguage}=requireFromPackage(require,"../../i18n");requireFromPackage(require,"../../lib/connectResilience").applyConnectResilience(require("node:net"));{const{SYS_PROMPT_ENV:e,isOwnSysPromptPath:t}=requireFromPackage(require,"../../lib/sysPromptHandoff"),r=process.env[e];if(t(r,require("node:os").tmpdir()))try{require("node:fs").unlinkSync(r)}catch{}}const{describeTokenForDebug:describeTokenForDebug}=requireFromPackage(require,"../../lib/debugRedaction"),{collectUpdateNotices:collectUpdateNotices,buildUpdateNoticeText:buildUpdateNoticeText,evaluateUpdateNotice:evaluateUpdateNotice,readLocalPackageVersion:readLocalPackageVersion}=require("./mcp-version-advisor.cjs"),{shouldAutoUpdate:shouldAutoUpdate,buildAutoUpdateNoticeText:buildAutoUpdateNoticeText,updateMcpOnDisk:updateMcpOnDisk}=require("./auto-update.cjs"),{extractDownloadedPackage:extractDownloadedPackage,formatInstallFailure:formatInstallFailure}=require("./install-package.cjs"),spawn=require("cross-spawn"),{StringDecoder:StringDecoder}=require("string_decoder"),path=require("path"),fs=require("fs"),os=require("os"),dotenvLocalPath=path.join(__dirname,"../../.env.local"),dotenvPath=path.join(__dirname,"../../.env");fs.existsSync(dotenvLocalPath)?(require("dotenv").config({path:dotenvLocalPath}),logger.debug("[MCP Server] Loaded .env.local")):fs.existsSync(dotenvPath)&&(require("dotenv").config({path:dotenvPath}),logger.debug("[MCP Server] Loaded .env"));const KEYWORD=process.env.MUSUHI_KEYWORD||"BL-要件定義",{TokenManager:TokenManager}=requireFromPackage(require,"../../auth/TokenManager");function resolveToken(){return TokenManager.loadTokenStringSync()}const PORTAL_URL_ENV=process.env.BLUELAMP_PORTAL_API_BASE_URL||process.env.PORTAL_URL||"",isDevEnv=PORTAL_URL_ENV.includes("localhost"),PORTAL_URL=PORTAL_URL_ENV||(isDevEnv?"http://localhost:8430/api/bluelamp":"https://api.motohi.jp/api/bluelamp"),LANGUAGE=process.env.MUSUHI_LANGUAGE||"ja",CATALOG_CACHE_FILE=path.join(os.homedir(),".bluelamp-vscode","gateway-catalog.json"),CATALOG_CACHE_VERSION=1,CHILD_READY_TIMEOUT_MS=3e4,CHILD_NOT_READY_TEXT="起動中です。数秒後に再試行してください";setLanguage(LANGUAGE);const LOG_DIR=path.join(os.homedir(),".bluelamp-vscode","logs"),LOG_FILE=path.join(LOG_DIR,"mcp.log");function log(e){const t=`[${(new Date).toISOString()}] ${e}\n`;fs.appendFileSync(LOG_FILE,t),logger.info(`[MCP Server] ${e}`)}fs.existsSync(LOG_DIR)||fs.mkdirSync(LOG_DIR,{recursive:!0}),log(`MCP Server started - Log file: ${LOG_FILE}`),log("Environment variables:"),log(` KEYWORD: ${KEYWORD}`),log(` TOKEN (起動時スナップショット): ${describeTokenForDebug(resolveToken())}`),log(` PORTAL_URL: ${PORTAL_URL}`),log(` LANGUAGE: ${LANGUAGE}`);const LEGACY_REGISTRY=path.join(os.homedir(),".bluelamp","registry.json");if(fs.existsSync(LEGACY_REGISTRY))try{fs.unlinkSync(LEGACY_REGISTRY),log(`[startup] Legacy registry.json removed: ${LEGACY_REGISTRY}`)}catch(e){log(`[startup] Failed to remove legacy registry.json: ${e.message}`)}const EXIT_CLOSE_GRACE_MS=2e3;class ChildMcpProcess{constructor(e,t,r,o){this.serviceId=e,this.command=t,this.args=(r||[]).map(e=>"string"==typeof e?e.replace(/^~\//,os.homedir()+"/"):e),this.env={...process.env,...o},this.process=null,this.tools=[],this.requestId=0,this.pending=new Map,this.buffer="",this.stdoutDecoder=new StringDecoder("utf8"),this.stderrDecoder=new StringDecoder("utf8"),this.stderrTail="",this._decodersEnded=!1}async start(){return new Promise((e,t)=>{let r=!1;const o=(e,t)=>{r||(r=!0,clearTimeout(i),e(t))},i=setTimeout(()=>{o(t,new Error(`Timeout: "${this.serviceId}" failed to start within 90s`)),this.stop()},9e4);try{this.process=spawn(this.command,this.args,{env:this.env,stdio:["pipe","pipe","pipe"]}),this.process.on("error",e=>{o(t,new Error(`Spawn error for "${this.serviceId}": ${e.message}`))}),this.process.stdin.on("error",e=>{log(`[ChildMcp:${this.serviceId}:stdin] ${e.message}`)}),this.process.on("close",()=>{this._flushDecoders("close")});const r=(e,r)=>{clearTimeout(this._exitCloseTimer);const i=this.stderrTail.trim();o(t,new Error(`"${this.serviceId}" exited before ready (code=${e}, signal=${r})${i?` | stderr: ${i}`:""}`)),this.pending.forEach(e=>e.reject(new Error("Process exited"))),this.pending.clear()};this.process.on("exit",(e,t)=>{log(`[ChildMcp] "${this.serviceId}" exited (code=${e}, signal=${t})`),this._exitCloseTimer=setTimeout(()=>r(e,t),2e3)}),this.process.on("close",(e,t)=>r(e,t)),this.process.on("close",()=>{if(this._decodersEnded)return;this._decodersEnded=!0;const e=this.stdoutDecoder.end(),t=this.stderrDecoder.end();e&&(this.buffer+=e,log(`[ChildMcp] "${this.serviceId}" stdout に半端なバイトが ${Buffer.byteLength(e)} バイト残っていた(子が多バイト文字の途中で終了)⇒ buffer へ流した。⛔ これは「壊れた文字」であって「失われた文字」ではない`)),t&&log(`[ChildMcp] "${this.serviceId}" stderr に半端なバイトが ${Buffer.byteLength(t)} バイト残っていた ⇒ ${JSON.stringify(t)}`)}),this.process.stderr.on("data",e=>{const t=this.stderrDecoder.write(e);this.stderrTail=sliceTailPreservingSurrogates(this.stderrTail+t,500),log(`[ChildMcp:${this.serviceId}:stderr] ${t.trim()}`)}),this.process.stdout.on("data",e=>{this.buffer+=this.stdoutDecoder.write(e),this._processBuffer()}),this._sendRequest("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"bluelamp-gateway",version:"1.0.0"}}).then(e=>(log(`[ChildMcp] "${this.serviceId}" initialized: ${JSON.stringify(e.serverInfo||{})}`),this._sendNotification("notifications/initialized",{}),this._sendRequest("tools/list",{}))).then(t=>{const r=t.tools||[];this.tools=r.map(e=>({...e,name:`${this.serviceId}__${e.name}`,_originalName:e.name})),log(`[ChildMcp] "${this.serviceId}" ready: ${this.tools.length} tools`),o(e,this.tools)}).catch(e=>{o(t,e)})}catch(e){o(t,e)}})}async callTool(e,t){return await this._sendRequest("tools/call",{name:e,arguments:t})}_flushDecoders(e){for(const[t,r]of[["stdout",this.stdoutDecoder],["stderr",this.stderrDecoder]]){let o="";try{o=r.end()}catch(e){log(`[ChildMcp:${this.serviceId}:${t}] decoder.end() が落ちた: ${e.message}`);continue}o&&log(`[ChildMcp:${this.serviceId}:${t}] 🚨 未完の多バイト列を ${e} 時に検出: ${JSON.stringify(o)}(${o.length} 文字・⛔ 黙って捨てていない)`)}}stop(){clearTimeout(this._exitCloseTimer),this.process&&(this.process.kill(),this.process=null),this.pending.forEach(e=>e.reject(new Error("Process stopped"))),this.pending.clear()}_sendRequest(e,t){return new Promise((r,o)=>{const i=++this.requestId,s=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:t})+"\n";this.pending.set(i,{resolve:r,reject:o});try{this.process.stdin.write(s)}catch(e){this.pending.delete(i),o(new Error(`Write error: ${e.message}`))}})}_sendNotification(e,t){const r=JSON.stringify({jsonrpc:"2.0",method:e,params:t})+"\n";try{this.process.stdin.write(r)}catch(e){log(`[ChildMcp] Notification write error: ${e.message}`)}}_processBuffer(){const e=this.buffer.split("\n");this.buffer=e.pop();for(const t of e){const e=t.trim();if(e)try{const t=JSON.parse(e);if(t.id&&this.pending.has(t.id)){const e=this.pending.get(t.id);this.pending.delete(t.id),t.error?e.reject(new Error(`JSON-RPC error: ${JSON.stringify(t.error)}`)):e.resolve(t.result)}}catch(t){log(`[ChildMcp:${this.serviceId}] Parse error: ${t.message} | line: ${e.substring(0,200)}`)}}}}class ChildMcpManager{constructor(){this.children=new Map,this.starting=new Map}async activateExternal(e,t){const r=new ChildMcpProcess(e,t.command,t.args||[],t.env||{}),o=await r.start();return this.children.set(e,{type:"external",process:r,tools:o,service:t}),o}beginActivateExternal(e,t){const r=this.children.get(e);if(r)return Promise.resolve({ok:!0,tools:r.tools||[]});const o=this.starting.get(e);if(o)return o;const i=this.activateExternal(e,t).then(e=>({ok:!0,tools:e}),e=>({ok:!1,error:e})).then(t=>(this.starting.delete(e),t));return this.starting.set(e,i),i}isStarting(e){return this.starting.has(e)}async waitForReady(e,t){if(this.children.has(e))return{ready:!0};const r=this.starting.get(e);if(!r)return{ready:!1,reason:"unknown"};let o=null;const i=new Promise(e=>{o=setTimeout(()=>e({timedOut:!0}),t),"function"==typeof o.unref&&o.unref()});try{const e=await Promise.race([r,i]);return e.timedOut?{ready:!1,reason:"timeout"}:e.ok?{ready:!0}:{ready:!1,reason:"failed",error:e.error}}finally{o&&clearTimeout(o)}}deactivate(e){const t=this.children.get(e);t&&("external"===t.type&&t.process&&t.process.stop(),this.children.delete(e))}isActive(e){return this.children.has(e)}getActiveTools(){const e=[];for(const t of this.children.values())e.push(...t.tools||[]);return e}async callTool(e,t){for(const[r,o]of this.children)if("external"===o.type){const r=o.tools.find(t=>t.name===e);if(r)return{found:!0,result:await o.process.callTool(r._originalName,t)}}return{found:!1}}getActiveServiceIds(){return[...this.children.keys()]}}class BlueLampServer{constructor(){this.childManager=new ChildMcpManager,this.updateNoticeText=null,this._autoUpdating=new Map,this._autoUpdateTried=new Set,this._autoUpdateRecords=[],this._childSettling=new Map,this._catalogTools=new Map,this._cloudProxyTools=new Map,this._catalogServices=new Map,this._needChildForSchema=new Set,this._catalogFromCache=!1,this._configRefresh=null,this.server=new Server({name:"bluelamp",version:"2.0.0"},{capabilities:{tools:{listChanged:!0}}}),this.setupHandlers()}checkAuth(){return resolveToken()?{ok:!0}:{ok:!1,error:"BlueLamp にログインしてください。ターミナルで `bluelamp1` を一度実行すると ~/.musuhi/portal-token.enc が作成されます。"}}buildToolList(){return buildGatewayToolList([{name:"load_knowledge",description:t("mcp.toolDescriptionLoadKnowledge"),annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{keyword:{type:"string",description:t("mcp.keywordDescription")}},required:["keyword"]}},{name:"search_mcp",description:'キーワードでインストール済みMCPサービスを検索します。使いたい機能を自然言語で説明してください。(例: "ブラウザ操作", "メール送信", "画像生成")',inputSchema:{type:"object",properties:{query:{type:"string",description:"検索キーワード(自然言語OK)"}},required:["query"]}},{name:"activate_service",description:"deactivate_service で一覧から外した MCP を、道具一覧に戻します(deactivate を戻すだけ)。権限のある MCP は最初から一覧に出ているので、通常このツールを撃つ必要はありません。",inputSchema:{type:"object",properties:{service_id:{type:"string",description:"サービスID"},always_on:{type:"boolean",description:"後方互換のため受け付けますが、一覧の可否には使いません(無視されます)"}},required:["service_id"]}},{name:"deactivate_service",description:"指定した MCP を道具一覧から外します(deactivated=true)。次の接続でも一覧に出なくなります。権限は変わらないので activate_service でいつでも戻せます。",inputSchema:{type:"object",properties:{service_id:{type:"string",description:"サービスID"}},required:["service_id"]}},{name:"restart_service",description:"MCPサービスのプロセスを再起動します。コード更新や設定変更の反映に使用します。",inputSchema:{type:"object",properties:{service_id:{type:"string",description:"サービスID"}},required:["service_id"]}},{name:"unregister_service",description:"MCPサービスをレジストリから完全に削除します。プロセスも停止します。",inputSchema:{type:"object",properties:{service_id:{type:"string",description:"削除するサービスID"}},required:["service_id"]}},{name:"register_service",description:"新しいMCPサービスをゲートウェイに登録します。",inputSchema:{type:"object",properties:{service_id:{type:"string",description:'サービスID(英数字、例: "microcms")'},name:{type:"string",description:"サービス表示名"},description:{type:"string",description:"サービスの説明"},tags:{type:"array",items:{type:"string"},description:"検索用タグ"},command:{type:"string",description:'実行コマンド("npx" or "node")'},args:{type:"array",items:{type:"string"},description:"コマンド引数"},env:{type:"object",description:"環境変数"}},required:["service_id","name","description","tags"]}},{name:"browse_mcp_store",description:"MCPストア(Portal)からインストール可能なMCP一覧を取得します。",inputSchema:{type:"object",properties:{},required:[]}},{name:"install_from_store",description:"MCP ストアから MCP を取得してこの機体に展開し、env と導入版をサーバに記録します。browse_mcp_store で見つけた mcp_id を指定してください。道具一覧に出るかどうかは権限で決まるので、権限の無い MCP をこれで一覧に出すことはできません(自分で作った MCP・共有された MCP は権限に含まれるため、何もしなくても一覧に出ます)。",inputSchema:{type:"object",properties:{mcp_id:{type:"string",description:"インストールするMCPのID"}},required:["mcp_id"]}},{name:"save_mcp_env",description:"MCPの環境変数(APIキー等)をサーバーに安全に保存します。ローカルには保存されません。次回起動時にサーバーから自動取得されます。解約時はアクセスできなくなります。",inputSchema:{type:"object",properties:{service_id:{type:"string",description:"MCP サービスID(例: heygen, gemini-image)"},env:{type:"object",description:'環境変数のキーと値(例: {"HEYGEN_API_KEY": "sk_xxx"})',additionalProperties:{type:"string"}}},required:["service_id","env"]}}],this._catalogTools,this.childManager.getActiveTools())}applyCatalog(e,t={}){const{catalog:r,cloudProxy:o,warnings:i,needChildForSchema:s}=buildCatalogRegistry(e);this._catalogTools=r,this._cloudProxyTools=o,this._catalogServices=new Map,this._needChildForSchema=new Set(s),this._catalogFromCache=!0===t.fromCache;for(const t of Array.isArray(e)?e:[])t&&t.mcpId&&this._catalogServices.set(t.mcpId,t);let n=0;for(const e of i)"no-input-schema"===e.reason?(n+=e.count,log(`[catalog] "${e.mcpId}" (${e.hostingType||"unknown"}): ${e.count}/${e.total} tools have no inputSchema — 一覧には出す(空 schema)。子を起こして実 schema で上書きする`)):log(`[catalog] "${e.mcpId}" (${e.hostingType||"unknown"}) skipped: ${e.reason}`);return n>0&&log(`[catalog] inputSchema 欠損の合計: ${n} 本 / ${this._needChildForSchema.size} service(一覧には出す。子を起こして実 schema で上書きする)`),log(`[catalog] ${r.size} tools registered from ${this._catalogServices.size} services (cloud_proxy: ${o.size})`),r}registerServiceInCatalog(e){const{catalog:t,cloudProxy:r,warnings:o}=buildCatalogRegistry([e]);for(const[e,r]of t)this._catalogTools.set(e,r);for(const[e,t]of r)this._cloudProxyTools.set(e,t);for(const e of o)log(`[catalog] "${e.mcpId}" (${e.hostingType||"unknown"}) skipped: ${e.reason}`);return e&&e.mcpId&&this._catalogServices.set(e.mcpId,e),t.size}unregisterServiceFromCatalog(e){const t=`${e}__`;let r=0;for(const e of[...this._catalogTools.keys()])e.startsWith(t)&&(this._catalogTools.delete(e),this._cloudProxyTools.delete(e),r++);return r}buildChildService(e,t){const r=path.join(os.homedir(),".claude","mcp-servers",e),o=t.entryPoint||"dist/index.js";return{name:t.name,description:t.description,type:"external",command:t.command||"node",args:t.args&&t.args.length?t.args:[path.join(r,o)],env:t.env||{}}}setupHandlers(){this.server.setRequestHandler(ListToolsRequestSchema,async()=>{const e=this.buildToolList(),t=this.childManager.getActiveServiceIds();return log(`[ListTools] ${e.length} tools (active: ${t.join(", ")||"none"})`),{tools:e}}),this.server.setRequestHandler(CallToolRequestSchema,async e=>{const{name:r,arguments:o}=e.params;log(`[CallTool] ${r}`);const i=resolveToken();if("load_knowledge"===r){const{keyword:e}=o;log(`[load_knowledge] keyword: ${e}`);try{const r=await getPromptFromPortal(e,i,LANGUAGE);if(!r||!r.success){const o=r?.error||t("mcp.knowledgeNotFound",{keyword:e});return{content:[{type:"text",text:`❌ ${t("mcp.portalApiFailed",{error:o})}`}],isError:!0}}const o="ja"!==LANGUAGE?"\n\n[Note] The user's preferred language is English.":"",s=[this.updateNoticeText,buildAutoUpdateNoticeText(this._autoUpdateRecords)].filter(Boolean).map(e=>`\n\n${e}`).join("");return{content:[{type:"text",text:`✅ ${t("mcp.knowledgeLoadSuccess")}\n\n${r.knowledge}${o}\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n${t("mcp.knowledgeApplied")}${s}`}]}}catch(e){return log(`[load_knowledge] Exception: ${e.message}`),{content:[{type:"text",text:`❌ ${t("mcp.knowledgeLoadError",{error:e.message})}`}],isError:!0}}}if("search_mcp"===r){const e=this.checkAuth();if(!e.ok)return{content:[{type:"text",text:`🔒 ${e.error}`}],isError:!0};if(!i)return{content:[{type:"text",text:"❌ 未認証です。MCPカタログの検索にはログインが必要です。"}],isError:!0};let t=[];try{const e=await searchMcpServices(o.query,i);if(!e.success)return{content:[{type:"text",text:`❌ MCPカタログ検索に失敗: ${e.error||"Unknown"}`}],isError:!0};t=(e.data||[]).map(e=>({id:e.mcp_id,service:{name:e.name,description:e.description,tags:[],alwaysOn:e.alwaysOn||!1},isInstalled:e.isInstalled||!1}))}catch(e){return log(`[search_mcp] Server search failed: ${e.message}`),{content:[{type:"text",text:`❌ MCPカタログ検索に失敗: ${e.message}`}],isError:!0}}if(0===t.length)return{content:[{type:"text",text:`🔍 「${o.query}」に一致するサービスはありません。\n\n別のキーワードで試すか、browse_mcp_storeでカタログを確認してください。`}]};let r=`🔍 「${o.query}」の検索結果(${t.length}件)\n\n`;for(const e of t.slice(0,10)){const t=e.id,o=e.service,i=this.childManager.isActive(t),s=!0===o.deactivated,n=e.isInstalled?"":" [未インストール]",a=s?" [一覧から外し中]":"";r+=`${s?"🚫":i?"🟢":"⚪"} **${o.name}**${a}${n} (id: \`${t}\`)\n`,r+=` ${o.description}\n\n`}return r+="一覧に戻す: activate_service | ストアから導入: install_from_store",{content:[{type:"text",text:r}]}}if("activate_service"===r){const e=this.checkAuth();if(!e.ok)return{content:[{type:"text",text:`🔒 ${e.error}`}],isError:!0};const{service_id:t}=o,r=await getGatewayConfig(i);if(!r.success)return{content:[{type:"text",text:`❌ サーバー設定の取得に失敗: ${r.error||"Unknown"}`}],isError:!0};const s=(r.data?.services||[]).find(e=>e.mcpId===t);if(!s)return{content:[{type:"text",text:`❌ サービス "${t}" はあなたの権限の中にありません(権限のある MCP は何もしなくても一覧に出ます)。`}],isError:!0};const n=await setServiceDeactivated(t,!1,i);if(!n.success)return{content:[{type:"text",text:`❌ "${t}" を一覧に戻せませんでした: ${n.error||"Unknown"}`}],isError:!0};log(`[activate] "${t}" deactivated=false (一覧に戻した)`);const a=this.registerServiceInCatalog({...s,deactivated:!1});if(0===a)return{content:[{type:"text",text:`❌ "${t}" には目録にツール定義がありません(tools が空)。`}],isError:!0};if("cloud_proxy"===s.hostingType){log(`[activate] "${t}" (cloud_proxy) → ${a} proxy tools registered`);try{await this.server.notification({method:"notifications/tools/list_changed"})}catch(e){log(`[activate] notification error: ${e.message}`)}return{content:[{type:"text",text:`✅ "${s.name}" を一覧に戻しました(cloud_proxy ツール${a}個)`}]}}if(this.childManager.isActive(t)){try{await this.server.notification({method:"notifications/tools/list_changed"})}catch(e){log(`[activate] notification error: ${e.message}`)}return{content:[{type:"text",text:`✅ "${t}" を一覧に戻しました(子プロセスは既に起動済み)。`}]}}log(`[activate] "${t}" (${s.hostingType}) → ${a} catalog tools restored. Sending list_changed.`);try{await this.server.notification({method:"notifications/tools/list_changed"})}catch(e){log(`[activate] notification error: ${e.message}`)}return{content:[{type:"text",text:`✅ "${s.name}" を一覧に戻しました(ツール${a}個)。最初に呼ばれた時に自動で起動します。`}]}}if("deactivate_service"===r){const{service_id:e}=o;if(!i)return{content:[{type:"text",text:"🔒 未認証です。ログインが必要です。"}],isError:!0};const t=await setServiceDeactivated(e,!0,i);if(!t.success)return{content:[{type:"text",text:`❌ "${e}" を一覧から外せませんでした: ${t.error||"Unknown"}`}],isError:!0};log(`[deactivate] "${e}" deactivated=true (一覧から外した)`);const r=this.unregisterServiceFromCatalog(e);r>0&&log(`[deactivate] "${e}" → ${r} catalog tools removed`),this._catalogServices.delete(e);let s=!1;if(this.childManager.isActive(e)&&(this.childManager.deactivate(e),log(`[deactivate] "${e}" child process stopped`),s=!0),r>0||s)try{await this.server.notification({method:"notifications/tools/list_changed"})}catch(e){log(`[deactivate] notification error: ${e.message}`)}let n=`✅ "${e}" を道具一覧から外しました(deactivated=true)。`;return r>0&&(n+=` ツール${r}個を一覧から削除しました。`),s&&(n+=" 子プロセスを停止しました。"),n+=" 次の接続でも一覧に出ません。権限は変わっていないので activate_service で戻せます。",{content:[{type:"text",text:n}]}}if("restart_service"===r){const{service_id:e}=o,t=this.childManager.children.get(e),r=t?.service;if(!r)return isCloudProxyService(this._cloudProxyTools,e)?{content:[{type:"text",text:`ℹ️ "${e}" は cloud_proxy 方式のため、ローカルの再起動対象ではありません(子プロセスを持ちません)。\nサーバ側のツール更新は deploy で全利用者に反映されるので、再起動は不要です。\nツール一覧を取り直したいだけなら deactivate_service → activate_service を実行してください。`}]}:{content:[{type:"text",text:`❌ "${e}" の子プロセスは現在動いていません。道具を呼べば自動で起動します(restart は起動済みの子にだけ効きます)。`}],isError:!0};let s,n=r;if(i)try{const t=await getGatewayConfig(i);if(t.success){const o=(t.data?.services||[]).find(t=>t.mcpId===e);o&&o.env&&(n={...r,env:o.env},log(`[restart] "${e}" env refreshed from server (keys=${Object.keys(o.env).join(",")||"none"})`))}}catch(e){log(`[restart] env refresh failed (using cached): ${e.message}`)}this.childManager.deactivate(e),log(`[restart] "${e}" stopped`);try{s=await this.childManager.activateExternal(e,n)}catch(t){return log(`[restart] Failed "${e}": ${t.message}`),{content:[{type:"text",text:`❌ "${e}" の再起動に失敗しました: ${t.message}`}],isError:!0}}log(`[restart] "${e}" → ${s.length} tools. Sending list_changed.`);try{await this.server.notification({method:"notifications/tools/list_changed"})}catch(e){log(`[restart] notification error: ${e.message}`)}const a=s.map(e=>e.name).join(", ");return{content:[{type:"text",text:`🔄 "${n.name}" を再起動しました(ツール${s.length}個)\n\nツール: ${a||"(なし)"}`}]}}if("unregister_service"===r){const{service_id:e}=o;if(!i)return{content:[{type:"text",text:"🔒 未認証です。ログインが必要です。"}],isError:!0};this.childManager.isActive(e)&&(this.childManager.deactivate(e),log(`[unregister] "${e}" stopped`));const t=await uninstallMcpService(e,i);if(!t.success)return{content:[{type:"text",text:`❌ "${e}" のサーバー削除に失敗: ${t.error||"Unknown"}`}],isError:!0};log(`[unregister] "${e}" uninstalled from server`);try{await this.server.notification({method:"notifications/tools/list_changed"})}catch(e){log(`[unregister] notification error: ${e.message}`)}return{content:[{type:"text",text:`🗑️ "${e}" を削除しました。プロセスも停止済みです。`}]}}if("register_service"===r){const e=this.checkAuth();if(!e.ok)return{content:[{type:"text",text:`🔒 ${e.error}`}],isError:!0};const{service_id:t,env:r}=o;if(!i)return{content:[{type:"text",text:"🔒 未認証です。ログインが必要です。"}],isError:!0};const s=r||{},n=await installMcpService(t,!1,i,s);return n.success?(log(`[register] "${t}" installed on server`),{content:[{type:"text",text:`✅ サービス "${t}" をサーバーに登録しました。\n\n次のステップ:\n- save_mcp_env で APIキー等を設定\n- 次の接続で道具一覧に出ます(activate は不要です)`}]}):{content:[{type:"text",text:`❌ "${t}" の登録に失敗しました: ${n.error||"Unknown"}\n\n※ MCP はサーバーカタログに登録されている必要があります。browse_mcp_store で確認してください。`}],isError:!0}}if("save_mcp_env"===r){const e=this.checkAuth();if(!e.ok)return{content:[{type:"text",text:`🔒 ${e.error}`}],isError:!0};const{service_id:t,env:r}=o;if(!t||!r||0===Object.keys(r).length)return{content:[{type:"text",text:"❌ service_id と env(キー/値のペア)が必要です"}],isError:!0};log(`[save_mcp_env] ${t}: ${Object.keys(r).join(", ")}`);try{const e=await updateMcpEnv(t,r,i);if(!e.success)return{content:[{type:"text",text:`❌ サーバー保存失敗: ${e.error}`}],isError:!0};const o=Object.keys(r).join(", ");return e.warning?{content:[{type:"text",text:`🔐 環境変数をサーバーに保存しました\n\nサービス: ${t}\n保存キー: ${o}\n\n${e.warning}`}]}:{content:[{type:"text",text:`🔐 環境変数をサーバーに保存しました\n\nサービス: ${t}\n保存キー: ${o}\n\n※ ローカルには保存されません。次回起動時にサーバーから自動取得されます。`}]}}catch(e){return log(`[save_mcp_env] error: ${e.message}`),{content:[{type:"text",text:`❌ ${e.message}`}],isError:!0}}}if("browse_mcp_store"===r){log("[browse_mcp_store]");try{const e=await listAvailableMcps({},i,LANGUAGE);if(!e||!e.success)return{content:[{type:"text",text:`❌ MCPカタログの取得に失敗: ${e?.error||"Unknown"}`}],isError:!0};const t=e.data||[];if(0===t.length)return{content:[{type:"text",text:"📦 インストール可能なMCPはありません。"}]};let r=`📦 MCPストア一覧 (${t.length}件)\n\n`;return t.forEach(e=>{const t=e.isOfficial?" [公式]":"";r+=`**${e.name}**${t}\n`,r+=` ID: ${e.mcpId}\n`,r+=` ${e.description}\n`,r+=` ツール数: ${e.toolCount}\n\n`}),r+='\nインストールするには: install_from_store(mcp_id: "MCP_ID")',{content:[{type:"text",text:r}]}}catch(e){return log(`[browse_mcp_store] error: ${e.message}`),{content:[{type:"text",text:`❌ ${e.message}`}],isError:!0}}}if("install_from_store"===r){const{mcp_id:e}=o;log(`[install_from_store] mcp_id=${e}`);try{const t=await downloadMcpPackage(e,i);if(!t||!t.success)return{content:[{type:"text",text:`❌ MCPダウンロードに失敗: ${t?.error||"Unknown"}`}],isError:!0};const r=t.data,o=r.packageSource||{},s=r.files||[];let n=o.hostingType||o.hosting&&o.hosting.type||null;if(i){let t=!1;try{const r=await getGatewayConfig(i);if(r.success){const o=(r.data?.services||[]).find(t=>t.mcpId===e);o&&(t=!0===o.alwaysOn,n||(n=o.hostingType))}}catch(e){}const r=await installMcpService(e,t,i);if(!r.success)return{content:[{type:"text",text:`❌ サーバー登録失敗: ${r.error||"Unknown"}`}],isError:!0};log(`[install_from_store] Server sync OK: ${e} (alwaysOn=${t})`)}if("cloud_proxy"===n){log(`[install_from_store] "${e}" is cloud_proxy, skipping local extract`);let t=`✅ MCP「${o.name||e}」をインストールしました(cloud_proxy)\n\n`;return t+="☁ クラウド実行のためローカル展開は不要です\n",o.installNotes&&(t+=`\n📝 ${o.installNotes}\n`),t+="\n権限に含まれていれば、次の接続で道具一覧に出ます(activate_service を撃つ必要はありません)。",{content:[{type:"text",text:t}]}}const a=path.join(os.homedir(),".claude","mcp-servers",e),c=await extractDownloadedPackage({mcpId:e,installDir:a,pkg:r});if("empty"===c.stage)return{content:[{type:"text",text:"❌ MCPパッケージにファイルが含まれていません。"}],isError:!0};if(!c.ok)return log(`[install_from_store] ${e} failed at ${c.stage}: ${c.error.message}`),{content:[{type:"text",text:formatInstallFailure(o.name||e,c)}],isError:!0};log(`[install_from_store] ${s.length} files written to ${a}`);let l=`✅ MCP「${o.name||e}」をインストールしました\n\n`;l+=`📁 インストール先: ${a}\n`,l+=`📄 ファイル数: ${s.length}\n`,o.installNotes&&(l+=`\n📝 ${o.installNotes}\n`);const d=(o.requiredEnvVars||[]).filter(e=>!process.env[e]);return d.length>0&&(l+="\n⚠️ 以下の環境変数を save_mcp_env で設定してください:\n",d.forEach(e=>{l+=` - ${e}\n`})),l+="\n権限に含まれていれば、次の接続で道具一覧に出ます(activate_service を撃つ必要はありません)。",{content:[{type:"text",text:l}]}}catch(e){return log(`[install_from_store] error: ${e.message}`),{content:[{type:"text",text:`❌ ${e.message}`}],isError:!0}}}if(this._cloudProxyTools&&this._cloudProxyTools.has(r)){const e=this._cloudProxyTools.get(r);log(`[callTool] Cloud proxy: ${r} → ${e.mcpId}/${e.toolName}`);try{const t=await callMcpToolProxy(e.mcpId,e.toolName,o,i);return t.success&&t.data?t.data.content?t.data:{content:[{type:"text",text:JSON.stringify(t.data,null,2)}]}:{content:[{type:"text",text:`❌ プロキシエラー: ${t.error||"Unknown"}`}],isError:!0}}catch(e){return log(`[callTool] Cloud proxy error "${r}": ${e.message}`),{content:[{type:"text",text:`❌ クラウドプロキシエラー: ${e.message}`}],isError:!0}}}{const e=(this._catalogTools.get(r)||{}).mcpId||String(r).split("__")[0];if(this._childSettling.has(e)&&!await this.waitForChildSettled(e,r))return{content:[{type:"text",text:CHILD_NOT_READY_TEXT}],isError:!0}}try{const{found:e,result:t}=await this.childManager.callTool(r,o);if(e)return t&&t.content?t:{content:[{type:"text",text:String(t)}]}}catch(e){return log(`[callTool] Error proxying "${r}": ${e.message}`),{content:[{type:"text",text:`❌ ツール実行エラー: ${e.message}`}],isError:!0}}const s=this._catalogTools.get(r);if(s&&"cloud_proxy"!==s.hostingType){const e=s.mcpId;this._catalogFromCache&&this._configRefresh&&(log(`[callTool] "${e}" は目録キャッシュ由来。起動仕様の到着を待つ。`),await this._configRefresh),this.startChildOnDemand(e);const t=await this.childManager.waitForReady(e,3e4);if(!t.ready){if("failed"===t.reason){const r=t.error?.message||String(t.error||"Unknown");return log(`[callTool] "${e}" failed to start: ${r}`),{content:[{type:"text",text:`❌ "${e}" の起動に失敗しました: ${r}`}],isError:!0}}return"timeout"===t.reason?(log(`[callTool] "${e}" not ready within 30000ms for "${r}".`),{content:[{type:"text",text:CHILD_NOT_READY_TEXT}],isError:!0}):(log(`[callTool] "${e}" could not be started for "${r}" (reason=${t.reason}).`),{content:[{type:"text",text:`❌ "${e}" を起動できませんでした(設定が見つかりません)。`}],isError:!0})}if(!await this.waitForChildSettled(e,r))return{content:[{type:"text",text:CHILD_NOT_READY_TEXT}],isError:!0};try{const{found:t,result:i}=await this.childManager.callTool(r,o);if(t)return i&&i.content?i:{content:[{type:"text",text:String(i)}]};log(`[callTool] "${r}" is in catalog but child "${e}" does not have it.`)}catch(e){return log(`[callTool] Error proxying "${r}" after ready: ${e.message}`),{content:[{type:"text",text:`❌ ツール実行エラー: ${e.message}`}],isError:!0}}}return{content:[{type:"text",text:`❌ Unknown tool: ${r}`}],isError:!0}})}startChildrenForMissingSchema(){let e=0;for(const t of this._needChildForSchema){const r=this._catalogServices.get(t);if(r)if("cloud_proxy"!==r.hostingType){if(!this.childManager.isActive(t)&&!this.childManager.isStarting(t)){log(`[schemaChild] "${t}" (${r.hostingType}) を起こして実 schema を取りに行く`);try{this.startChildOnDemand(t),e++}catch(e){log(`[schemaChild] "${t}" の起動に失敗: ${e.message}(⛔ 席は落とさない)`)}}}else log(`[schemaChild] "${t}" は cloud_proxy のため子を起こせない。schema 欠損の道具は一覧に出ない。`)}return log(`[schemaChild] ${e} service(=目録に schema が無い道具を持つ service の数)`),e}async loadCatalog(e){if(!e)return log("[catalog] No token, starting with no catalog tools."),null;let t=[];try{const r=await getGatewayConfig(e);if(!r.success)return log(`[catalog] Server config failed: ${r.error||"Unknown"}. Starting with no services.`),null;t=r.data?.services||[],log(`[catalog] Server config: ${t.length} services`),this.applyCatalog(t)}catch(e){return log(`[catalog] Server config error: ${e.message}. Starting with no services.`),null}try{const e=collectUpdateNotices(t);this.updateNoticeText=buildUpdateNoticeText(e);for(const t of e)"not-applicable"!==t.status&&log(`[versionCheck] ${t.mcpId}: ${t.status} (${t.reason}) catalog=${t.catalogVersion} local=${t.localVersion}`)}catch(e){log(`[versionCheck] skipped: ${e.message}`)}return t}startChildOnDemand(e){const t=this._catalogServices.get(e);if(!t||!0===t.deactivated)return null;if("cloud_proxy"===t.hostingType)return null;if(this.childManager.isActive(e))return null;const r=this.childManager.isStarting(e),o=this.childManager.beginActivateExternal(e,this.buildChildService(e,t));if(r||log(`[startChild] "${e}" (${t.hostingType}) starting on demand...`),!this._childSettling.has(e)){const t=o.then(t=>this.reconcileChildWithCatalog(e,t)).catch(t=>log(`[startChild] "${e}" post-start error: ${t.message}`)).finally(()=>{this._childSettling.get(e)===t&&this._childSettling.delete(e)});this._childSettling.set(e,t)}return o}async waitForChildSettled(e,t){const r=this._childSettling.get(e);if(!r)return!0;let o=null;const i=new Promise(e=>{o=setTimeout(()=>e(!1),3e4),"function"==typeof o.unref&&o.unref()});try{const o=await Promise.race([r.then(()=>!0),i]);return o||log(`[callTool] "${e}" の突き合わせ(自動更新を含む)が 30000ms で済まない → "${t}" は転送しない`),o}finally{o&&clearTimeout(o)}}async reconcileChildWithCatalog(e,t,r={}){const o=decideCatalogReconciliation(this._catalogTools,e,t);if(this._autoUpdating.has(e)&&!r.fromAutoUpdate)return log(`[autoUpdate] "${e}" は更新中 → この突き合わせは見送る`),o;if(!r.fromAutoUpdate){const r=this.evaluateVersionOnDisk(e);if(shouldAutoUpdate({decision:o,notice:r,alreadyTried:this._autoUpdateTried.has(e)}).update){this._autoUpdateTried.add(e);const i=this.autoUpdateAndRestart(e,t,o,r);this._autoUpdating.set(e,i);try{return await i}finally{this._autoUpdating.delete(e)}}}if(!o.ready){const r=t&&t.error?`: ${t.error.message||t.error}`:"";return log(`[versionDrift] "${e}" not ready (${o.reason})${r} → 剪定も通知もしない`),o}if(!o.notify)return log(`[versionDrift] "${e}" matches catalog (${t.tools.length} tools) → no list_changed`),o;for(const e of o.prune)this._catalogTools.delete(e),this._cloudProxyTools.delete(e);const i=o.diff;log(`[versionDrift] "${e}" differs from catalog: +${i.added.length} -${i.removed.length} ~${i.changed.length} → list_changed`);try{await this.server.notification({method:"notifications/tools/list_changed"})}catch(e){log(`[versionDrift] notification error: ${e.message}`)}return o}evaluateVersionOnDisk(e){const t=this._catalogServices.get(e);return t?evaluateUpdateNotice({mcpId:e,hostingType:t.hostingType,catalogVersion:t.packageVersion,localVersion:readLocalPackageVersion(e,{entryPoint:t.entryPoint})}):null}async autoUpdateAndRestart(e,t,r,o){const i=this._catalogServices.get(e),s=path.join(os.homedir(),".claude","mcp-servers"),n=r.prune.length;log(`[autoUpdate] "${e}" disk=${o.localVersion} catalog=${o.catalogVersion} で ${n} 本が剪定される → 目録の版へ上げる`);const a=await updateMcpOnDisk({mcpId:e,installRoot:s,catalogVersion:o.catalogVersion,entryPoint:i&&i.entryPoint,readLocalVersion:()=>readLocalPackageVersion(e,{installRoot:s,entryPoint:i&&i.entryPoint}),download:()=>downloadMcpPackage(e,resolveToken()),extract:(t,r)=>extractDownloadedPackage({mcpId:e,installDir:t,pkg:r})});if(!a.ok)return log(`[autoUpdate] "${e}" 上げられなかった(${a.reason})→ 今の版のまま剪定する`),this.reconcileChildWithCatalog(e,t,{fromAutoUpdate:!0});this.childManager.deactivate(e);const c=await this.childManager.beginActivateExternal(e,this.buildChildService(e,i));return c.ok?(log(`[autoUpdate] ${e} ${a.from} → ${a.to}(剪定されるはずだった口: ${n} 本)${"other"===a.by?"・同じ機体の別の席が上げた版を使う":""}`),this._autoUpdateRecords.push({mcpId:e,from:a.from,to:a.to,prunedWouldBe:n}),this.reconcileChildWithCatalog(e,c,{fromAutoUpdate:!0})):(log(`[autoUpdate] "${e}" ${a.from} → ${a.to} の後、子が起きなかった: ${c.error&&c.error.message}`),this.reconcileChildWithCatalog(e,c,{fromAutoUpdate:!0}))}persistCatalogCache(e,t){return!!e&&writeCatalogCache(CATALOG_CACHE_FILE,e,catalogCacheFingerprint(t),log)}toolListSignature(){return stableJson(this.buildToolList().map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema})))}async refreshCatalogInBackground(e){const t=this.toolListSignature();let r;try{r=await this.loadCatalog(e)}catch(e){return log(`[catalogRefresh] failed, keeping cached catalog: ${e.message}`),{notified:!1,reason:"failed"}}if(t===this.toolListSignature())return log("[catalogRefresh] server catalog matches cache → no list_changed"),this.persistCatalogCache(r,e),{notified:!1,reason:"same"};log("[catalogRefresh] server catalog differs from cache → list_changed");try{await this.server.notification({method:"notifications/tools/list_changed"})}catch(e){log(`[catalogRefresh] notification error: ${e.message}`)}return this.persistCatalogCache(r,e),{notified:!0,reason:"diff"}}async run(){const e=resolveToken(),t=catalogCacheFingerprint(e),r=readCatalogCache(CATALOG_CACHE_FILE,t,log);let o=null;r?(this.applyCatalog(r,{fromCache:!0}),log(`[catalogCache] ${this._catalogTools.size} tools from cache (HTTP は待たない)`)):(log("[catalogCache] no usable cache, waiting for server config"),o=await this.loadCatalog(e));const i=new StdioServerTransport;await this.server.connect(i),log(`[Gateway] BlueLamp Gateway v2.0.0 started. (${this._catalogTools.size} catalog tools available at connect)`),this.persistCatalogCache(o,e),r?(this._configRefresh=this.refreshCatalogInBackground(e).catch(e=>(log(`[catalogRefresh] unexpected: ${e.message}`),{notified:!1,reason:"failed"})),this._configRefresh.then(()=>this.startChildrenForMissingSchema()).catch(e=>log(`[schemaChild] deferred start failed: ${e.message}`))):this.startChildrenForMissingSchema();const s=resolveToken();if(KEYWORD&&s){log(`[Gateway] Auto-loading knowledge for keyword: ${KEYWORD}`);const e=await getPromptFromPortal(KEYWORD,s,LANGUAGE);e&&e.success?log(`[Gateway] Auto-load successful: ${e.title}`):log(`[Gateway] Auto-load failed for keyword: ${KEYWORD}`)}}}function buildCatalogRegistry(e){const t=new Map,r=new Map,o=[],i=[];for(const s of Array.isArray(e)?e:[]){if(!s||"string"!=typeof s.mcpId||!s.mcpId)continue;const e=s.hostingType||null;if(!0===s.deactivated)continue;const n=Array.isArray(s.tools)?s.tools:[];if(0===n.length){o.push({mcpId:s.mcpId,hostingType:e,reason:"no-tools"});continue}const a=[];for(const i of n){if(!i||"string"!=typeof i.name||!i.name){o.push({mcpId:s.mcpId,hostingType:e,reason:"unnamed-tool"});continue}i.inputSchema&&"object"==typeof i.inputSchema||a.push(i.name);const n=`${s.mcpId}__${i.name}`,c={name:n,mcpId:s.mcpId,toolName:i.name,hostingType:e,description:i.description,inputSchema:i.inputSchema};t.set(n,c),"cloud_proxy"===e&&r.set(n,{mcpId:s.mcpId,toolName:i.name,description:i.description,inputSchema:i.inputSchema})}a.length>0&&(o.push({mcpId:s.mcpId,hostingType:e,reason:"no-input-schema",count:a.length,total:n.length,tools:a}),i.push(s.mcpId))}return{catalog:t,cloudProxy:r,warnings:o,needChildForSchema:i}}function catalogEntryToTool(e){return{name:e.name,description:e.description||`[${e.mcpId}] ${e.toolName}`,inputSchema:e.inputSchema||{type:"object",properties:{}}}}function buildGatewayToolList(e,t,r){const o=new Map;for(const t of Array.isArray(e)?e:[])t&&t.name&&o.set(t.name,t);if(t&&"function"==typeof t.values)for(const e of t.values())o.has(e.name)||o.set(e.name,catalogEntryToTool(e));for(const e of Array.isArray(r)?r:[])e&&e.name&&o.set(e.name,e);return[...o.values()]}function sanitizeServicesForCache(e){return(Array.isArray(e)?e:[]).filter(e=>e&&"string"==typeof e.mcpId&&e.mcpId).map(e=>({mcpId:e.mcpId,name:e.name,description:e.description,hostingType:e.hostingType||null,deactivated:!0===e.deactivated,tools:(Array.isArray(e.tools)?e.tools:[]).filter(e=>e&&"string"==typeof e.name&&e.name).map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema}))}))}function catalogCacheFingerprint(e){return e?require("crypto").createHash("sha256").update(String(e)).digest("hex").slice(0,16):null}function sliceTailPreservingSurrogates(e,t){const r=String(null==e?"":e);if(r.length<=t)return r;const o=r.slice(-t),i=o.charCodeAt(0);return i>=56320&&i<=57343?o.slice(1):o}function stableJson(e){return void 0===e?"null":null===e||"object"!=typeof e?JSON.stringify(e):Array.isArray(e)?`[${e.map(stableJson).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${stableJson(e[t])}`).join(",")}}`}function diffChildToolsAgainstCatalog(e,t,r){const o=`${t}__`,i=new Set;if(e&&"function"==typeof e.keys)for(const t of e.keys())"string"==typeof t&&t.startsWith(o)&&i.add(t);const s=[],n=[],a=new Set;for(const t of Array.isArray(r)?r:[]){if(!t||!t.name)continue;a.add(t.name);const r=e&&"function"==typeof e.get?e.get(t.name):void 0;r?stableJson(r.description)===stableJson(t.description)&&stableJson(r.inputSchema)===stableJson(t.inputSchema)||n.push(t.name):s.push(t.name)}const c=[...i].filter(e=>!a.has(e));return{added:s,removed:c,changed:n,hasDiff:s.length+c.length+n.length>0}}function decideCatalogReconciliation(e,t,r){if(!r||!0!==r.ok||!Array.isArray(r.tools))return{ready:!1,prune:[],notify:!1,reason:r&&r.reason||"not-ready",diff:null};const o=diffChildToolsAgainstCatalog(e,t,r.tools);return{ready:!0,prune:o.removed,notify:o.hasDiff,reason:"ready",diff:o}}function readCatalogCache(e,t,r){const o=r||(()=>{});if(!t)return null;let i,s;try{i=fs.readFileSync(e,"utf8")}catch(e){return"ENOENT"!==e.code&&o(`[catalogCache] read failed: ${e.message}`),null}try{s=JSON.parse(i)}catch(e){return o(`[catalogCache] broken JSON, ignoring: ${e.message}`),null}return s&&1===s.version?s.tokenFingerprint!==t?(o("[catalogCache] fingerprint mismatch (口座が違う), ignoring"),null):Array.isArray(s.services)?s.services:(o("[catalogCache] services が配列でない, ignoring"),null):(o(`[catalogCache] version mismatch (${s&&s.version}), ignoring`),null)}function writeCatalogCache(e,t,r,o){const i=o||(()=>{});if(!r)return!1;try{fs.mkdirSync(path.dirname(e),{recursive:!0});const o={version:1,tokenFingerprint:r,savedAt:(new Date).toISOString(),services:sanitizeServicesForCache(t)},i=`${e}.${process.pid}.tmp`;return fs.writeFileSync(i,JSON.stringify(o),{mode:384}),fs.renameSync(i,e),!0}catch(e){return i(`[catalogCache] write failed: ${e.message}`),!1}}function isCloudProxyService(e,t){if(!e||"function"!=typeof e.keys)return!1;const r=`${t}__`;for(const t of e.keys())if("string"==typeof t&&t.startsWith(r))return!0;return!1}if(module.exports={ChildMcpProcess:ChildMcpProcess,ChildMcpManager:ChildMcpManager,BlueLampServer:BlueLampServer,isCloudProxyService:isCloudProxyService,buildCatalogRegistry:buildCatalogRegistry,buildGatewayToolList:buildGatewayToolList,catalogEntryToTool:catalogEntryToTool,diffChildToolsAgainstCatalog:diffChildToolsAgainstCatalog,decideCatalogReconciliation:decideCatalogReconciliation,sanitizeServicesForCache:sanitizeServicesForCache,catalogCacheFingerprint:catalogCacheFingerprint,readCatalogCache:readCatalogCache,writeCatalogCache:writeCatalogCache,CATALOG_CACHE_FILE:CATALOG_CACHE_FILE,CATALOG_CACHE_VERSION:1,stableJson:stableJson,sliceTailPreservingSurrogates:sliceTailPreservingSurrogates,CHILD_READY_TIMEOUT_MS:3e4,CHILD_NOT_READY_TEXT:CHILD_NOT_READY_TEXT},require.main===module){const e=new BlueLampServer;let t=!1;const r=r=>{if(!t){t=!0;try{log(`[Gateway] Shutdown (${r}) - cleaning up children...`)}catch(e){}if(e&&e.childManager&&e.childManager.children)for(const[t,r]of e.childManager.children)try{try{log(`[Gateway] Stopping child: ${t}`)}catch(e){}r&&"external"===r.type&&r.process&&"function"==typeof r.process.stop&&r.process.stop()}catch(e){}setTimeout(()=>process.exit(0),200).unref()}};process.on("SIGTERM",()=>r("SIGTERM")),process.on("SIGINT",()=>r("SIGINT")),process.on("SIGHUP",()=>r("SIGHUP")),process.stdin.on("end",()=>r("stdin-end")),process.stdin.on("close",()=>r("stdin-close")),process.on("exit",()=>{if(e&&e.childManager&&e.childManager.children)for(const[t,r]of e.childManager.children)try{r&&r.process&&r.process.process&&"function"==typeof r.process.process.kill&&r.process.process.kill("SIGKILL")}catch(e){}}),e.run().catch(e=>{log(`[Gateway] Fatal: ${e.message}`),process.exit(1)})}
|
|
2
|
+
const{Server:Server}=require("@modelcontextprotocol/sdk/server/index.js"),{StdioServerTransport:StdioServerTransport}=require("@modelcontextprotocol/sdk/server/stdio.js"),{CallToolRequestSchema:CallToolRequestSchema,ListToolsRequestSchema:ListToolsRequestSchema}=require("@modelcontextprotocol/sdk/types.js"),{getPromptFromPortal:getPromptFromPortal,listAvailableMcps:listAvailableMcps,downloadMcpPackage:downloadMcpPackage,getGatewayConfig:getGatewayConfig,searchMcpServices:searchMcpServices,installMcpService:installMcpService,setServiceDeactivated:setServiceDeactivated,uninstallMcpService:uninstallMcpService,updateMcpEnv:updateMcpEnv,callMcpToolProxy:callMcpToolProxy}=require("./portal-api-client.cjs"),{requireFromPackage:requireFromPackage}=require("../requireFromPackage.cjs"),{logger:logger}=requireFromPackage(require,"../../utils/logger"),{t:t,setLanguage:setLanguage}=requireFromPackage(require,"../../i18n");requireFromPackage(require,"../../lib/connectResilience").applyConnectResilience(require("node:net"));{const{SYS_PROMPT_ENV:e,isOwnSysPromptPath:t}=requireFromPackage(require,"../../lib/sysPromptHandoff"),r=process.env[e];if(t(r,require("node:os").tmpdir()))try{require("node:fs").unlinkSync(r)}catch{}}const{describeTokenForDebug:describeTokenForDebug}=requireFromPackage(require,"../../lib/debugRedaction"),{collectUpdateNotices:collectUpdateNotices,buildUpdateNoticeText:buildUpdateNoticeText,evaluateUpdateNotice:evaluateUpdateNotice,readLocalPackageVersion:readLocalPackageVersion}=require("./mcp-version-advisor.cjs"),{shouldAutoUpdate:shouldAutoUpdate,buildAutoUpdateNoticeText:buildAutoUpdateNoticeText,updateMcpOnDisk:updateMcpOnDisk}=require("./auto-update.cjs"),{extractDownloadedPackage:extractDownloadedPackage,formatInstallFailure:formatInstallFailure}=require("./install-package.cjs"),spawn=require("cross-spawn"),{StringDecoder:StringDecoder}=require("string_decoder"),path=require("path"),fs=require("fs"),os=require("os"),dotenvLocalPath=path.join(__dirname,"../../.env.local"),dotenvPath=path.join(__dirname,"../../.env");fs.existsSync(dotenvLocalPath)?(require("dotenv").config({path:dotenvLocalPath}),logger.debug("[MCP Server] Loaded .env.local")):fs.existsSync(dotenvPath)&&(require("dotenv").config({path:dotenvPath}),logger.debug("[MCP Server] Loaded .env"));const KEYWORD=process.env.MUSUHI_KEYWORD||"BL-要件定義",{TokenManager:TokenManager}=requireFromPackage(require,"../../auth/TokenManager");function resolveToken(){return TokenManager.loadTokenStringSync()}const PORTAL_URL_ENV=process.env.BLUELAMP_PORTAL_API_BASE_URL||process.env.PORTAL_URL||"",isDevEnv=PORTAL_URL_ENV.includes("localhost"),PORTAL_URL=PORTAL_URL_ENV||(isDevEnv?"http://localhost:8430/api/bluelamp":"https://api.motohi.jp/api/bluelamp"),LANGUAGE=process.env.MUSUHI_LANGUAGE||"ja",CATALOG_CACHE_FILE=path.join(os.homedir(),".bluelamp-vscode","gateway-catalog.json"),CATALOG_CACHE_VERSION=1,CHILD_READY_TIMEOUT_MS=3e4,CHILD_NOT_READY_TEXT="起動中です。数秒後に再試行してください";setLanguage(LANGUAGE);const LOG_DIR=path.join(os.homedir(),".bluelamp-vscode","logs"),LOG_FILE=path.join(LOG_DIR,"mcp.log");function log(e){const t=`[${(new Date).toISOString()}] ${e}\n`;fs.appendFileSync(LOG_FILE,t),logger.info(`[MCP Server] ${e}`)}fs.existsSync(LOG_DIR)||fs.mkdirSync(LOG_DIR,{recursive:!0}),log(`MCP Server started - Log file: ${LOG_FILE}`),log("Environment variables:"),log(" KEYWORD: "+(KEYWORD?"set":"unset")),log(` TOKEN (起動時スナップショット): ${describeTokenForDebug(resolveToken())}`),log(` PORTAL_URL: ${PORTAL_URL}`),log(` LANGUAGE: ${LANGUAGE}`);const LEGACY_REGISTRY=path.join(os.homedir(),".bluelamp","registry.json");if(fs.existsSync(LEGACY_REGISTRY))try{fs.unlinkSync(LEGACY_REGISTRY),log(`[startup] Legacy registry.json removed: ${LEGACY_REGISTRY}`)}catch(e){log(`[startup] Failed to remove legacy registry.json: ${e.message}`)}const EXIT_CLOSE_GRACE_MS=2e3;class ChildMcpProcess{constructor(e,t,r,o){this.serviceId=e,this.command=t,this.args=(r||[]).map(e=>"string"==typeof e?e.replace(/^~\//,os.homedir()+"/"):e),this.env={...process.env,...o},this.process=null,this.tools=[],this.requestId=0,this.pending=new Map,this.buffer="",this.stdoutDecoder=new StringDecoder("utf8"),this.stderrDecoder=new StringDecoder("utf8"),this.stderrTail="",this._decodersEnded=!1}async start(){return new Promise((e,t)=>{let r=!1;const o=(e,t)=>{r||(r=!0,clearTimeout(i),e(t))},i=setTimeout(()=>{o(t,new Error(`Timeout: "${this.serviceId}" failed to start within 90s`)),this.stop()},9e4);try{this.process=spawn(this.command,this.args,{env:this.env,stdio:["pipe","pipe","pipe"]}),this.process.on("error",e=>{o(t,new Error(`Spawn error for "${this.serviceId}": ${e.message}`))}),this.process.stdin.on("error",e=>{log(`[ChildMcp:${this.serviceId}:stdin] ${e.message}`)}),this.process.on("close",()=>{this._flushDecoders("close")});const r=(e,r)=>{clearTimeout(this._exitCloseTimer);const i=this.stderrTail.trim();o(t,new Error(`"${this.serviceId}" exited before ready (code=${e}, signal=${r})${i?` | stderr: ${i}`:""}`)),this.pending.forEach(e=>e.reject(new Error("Process exited"))),this.pending.clear()};this.process.on("exit",(e,t)=>{log(`[ChildMcp] "${this.serviceId}" exited (code=${e}, signal=${t})`),this._exitCloseTimer=setTimeout(()=>r(e,t),2e3)}),this.process.on("close",(e,t)=>r(e,t)),this.process.on("close",()=>{if(this._decodersEnded)return;this._decodersEnded=!0;const e=this.stdoutDecoder.end(),t=this.stderrDecoder.end();e&&(this.buffer+=e,log(`[ChildMcp] "${this.serviceId}" stdout に半端なバイトが ${Buffer.byteLength(e)} バイト残っていた(子が多バイト文字の途中で終了)⇒ buffer へ流した。⛔ これは「壊れた文字」であって「失われた文字」ではない`)),t&&log(`[ChildMcp] "${this.serviceId}" stderr に半端なバイトが ${Buffer.byteLength(t)} バイト残っていた ⇒ ${JSON.stringify(t)}`)}),this.process.stderr.on("data",e=>{const t=this.stderrDecoder.write(e);this.stderrTail=sliceTailPreservingSurrogates(this.stderrTail+t,500),log(`[ChildMcp:${this.serviceId}:stderr] ${t.trim()}`)}),this.process.stdout.on("data",e=>{this.buffer+=this.stdoutDecoder.write(e),this._processBuffer()}),this._sendRequest("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"bluelamp-gateway",version:"1.0.0"}}).then(e=>(log(`[ChildMcp] "${this.serviceId}" initialized: ${JSON.stringify(e.serverInfo||{})}`),this._sendNotification("notifications/initialized",{}),this._sendRequest("tools/list",{}))).then(t=>{const r=t.tools||[];this.tools=r.map(e=>({...e,name:`${this.serviceId}__${e.name}`,_originalName:e.name})),log(`[ChildMcp] "${this.serviceId}" ready: ${this.tools.length} tools`),o(e,this.tools)}).catch(e=>{o(t,e)})}catch(e){o(t,e)}})}async callTool(e,t){return await this._sendRequest("tools/call",{name:e,arguments:t})}_flushDecoders(e){for(const[t,r]of[["stdout",this.stdoutDecoder],["stderr",this.stderrDecoder]]){let o="";try{o=r.end()}catch(e){log(`[ChildMcp:${this.serviceId}:${t}] decoder.end() が落ちた: ${e.message}`);continue}o&&log(`[ChildMcp:${this.serviceId}:${t}] 🚨 未完の多バイト列を ${e} 時に検出: ${JSON.stringify(o)}(${o.length} 文字・⛔ 黙って捨てていない)`)}}stop(){clearTimeout(this._exitCloseTimer),this.process&&(this.process.kill(),this.process=null),this.pending.forEach(e=>e.reject(new Error("Process stopped"))),this.pending.clear()}_sendRequest(e,t){return new Promise((r,o)=>{const i=++this.requestId,s=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:t})+"\n";this.pending.set(i,{resolve:r,reject:o});try{this.process.stdin.write(s)}catch(e){this.pending.delete(i),o(new Error(`Write error: ${e.message}`))}})}_sendNotification(e,t){const r=JSON.stringify({jsonrpc:"2.0",method:e,params:t})+"\n";try{this.process.stdin.write(r)}catch(e){log(`[ChildMcp] Notification write error: ${e.message}`)}}_processBuffer(){const e=this.buffer.split("\n");this.buffer=e.pop();for(const t of e){const e=t.trim();if(e)try{const t=JSON.parse(e);if(t.id&&this.pending.has(t.id)){const e=this.pending.get(t.id);this.pending.delete(t.id),t.error?e.reject(new Error(`JSON-RPC error: ${JSON.stringify(t.error)}`)):e.resolve(t.result)}}catch(t){log(`[ChildMcp:${this.serviceId}] Parse error: ${t.message} | line: ${e.substring(0,200)}`)}}}}class ChildMcpManager{constructor(){this.children=new Map,this.starting=new Map}async activateExternal(e,t){const r=new ChildMcpProcess(e,t.command,t.args||[],t.env||{}),o=await r.start();return this.children.set(e,{type:"external",process:r,tools:o,service:t}),o}beginActivateExternal(e,t){const r=this.children.get(e);if(r)return Promise.resolve({ok:!0,tools:r.tools||[]});const o=this.starting.get(e);if(o)return o;const i=this.activateExternal(e,t).then(e=>({ok:!0,tools:e}),e=>({ok:!1,error:e})).then(t=>(this.starting.delete(e),t));return this.starting.set(e,i),i}isStarting(e){return this.starting.has(e)}async waitForReady(e,t){if(this.children.has(e))return{ready:!0};const r=this.starting.get(e);if(!r)return{ready:!1,reason:"unknown"};let o=null;const i=new Promise(e=>{o=setTimeout(()=>e({timedOut:!0}),t),"function"==typeof o.unref&&o.unref()});try{const e=await Promise.race([r,i]);return e.timedOut?{ready:!1,reason:"timeout"}:e.ok?{ready:!0}:{ready:!1,reason:"failed",error:e.error}}finally{o&&clearTimeout(o)}}deactivate(e){const t=this.children.get(e);t&&("external"===t.type&&t.process&&t.process.stop(),this.children.delete(e))}isActive(e){return this.children.has(e)}getActiveTools(){const e=[];for(const t of this.children.values())e.push(...t.tools||[]);return e}async callTool(e,t){for(const[r,o]of this.children)if("external"===o.type){const r=o.tools.find(t=>t.name===e);if(r)return{found:!0,result:await o.process.callTool(r._originalName,t)}}return{found:!1}}getActiveServiceIds(){return[...this.children.keys()]}}class BlueLampServer{constructor(){this.childManager=new ChildMcpManager,this.updateNoticeText=null,this._autoUpdating=new Map,this._autoUpdateTried=new Set,this._autoUpdateRecords=[],this._childSettling=new Map,this._catalogTools=new Map,this._cloudProxyTools=new Map,this._catalogServices=new Map,this._needChildForSchema=new Set,this._catalogFromCache=!1,this._configRefresh=null,this.server=new Server({name:"bluelamp",version:"2.0.0"},{capabilities:{tools:{listChanged:!0}}}),this.setupHandlers()}checkAuth(){return resolveToken()?{ok:!0}:{ok:!1,error:"BlueLamp にログインしてください。ターミナルで `bluelamp1` を一度実行すると ~/.musuhi/portal-token.enc が作成されます。"}}buildToolList(){return buildGatewayToolList([{name:"load_knowledge",description:t("mcp.toolDescriptionLoadKnowledge"),annotations:{readOnlyHint:!0,idempotentHint:!0},inputSchema:{type:"object",properties:{keyword:{type:"string",description:t("mcp.keywordDescription")}},required:["keyword"]}},{name:"search_mcp",description:'キーワードでインストール済みMCPサービスを検索します。使いたい機能を自然言語で説明してください。(例: "ブラウザ操作", "メール送信", "画像生成")',inputSchema:{type:"object",properties:{query:{type:"string",description:"検索キーワード(自然言語OK)"}},required:["query"]}},{name:"activate_service",description:"deactivate_service で一覧から外した MCP を、道具一覧に戻します(deactivate を戻すだけ)。権限のある MCP は最初から一覧に出ているので、通常このツールを撃つ必要はありません。",inputSchema:{type:"object",properties:{service_id:{type:"string",description:"サービスID"},always_on:{type:"boolean",description:"後方互換のため受け付けますが、一覧の可否には使いません(無視されます)"}},required:["service_id"]}},{name:"deactivate_service",description:"指定した MCP を道具一覧から外します(deactivated=true)。次の接続でも一覧に出なくなります。権限は変わらないので activate_service でいつでも戻せます。",inputSchema:{type:"object",properties:{service_id:{type:"string",description:"サービスID"}},required:["service_id"]}},{name:"restart_service",description:"MCPサービスのプロセスを再起動します。コード更新や設定変更の反映に使用します。",inputSchema:{type:"object",properties:{service_id:{type:"string",description:"サービスID"}},required:["service_id"]}},{name:"unregister_service",description:"MCPサービスをレジストリから完全に削除します。プロセスも停止します。",inputSchema:{type:"object",properties:{service_id:{type:"string",description:"削除するサービスID"}},required:["service_id"]}},{name:"register_service",description:"新しいMCPサービスをゲートウェイに登録します。",inputSchema:{type:"object",properties:{service_id:{type:"string",description:'サービスID(英数字、例: "microcms")'},name:{type:"string",description:"サービス表示名"},description:{type:"string",description:"サービスの説明"},tags:{type:"array",items:{type:"string"},description:"検索用タグ"},command:{type:"string",description:'実行コマンド("npx" or "node")'},args:{type:"array",items:{type:"string"},description:"コマンド引数"},env:{type:"object",description:"環境変数"}},required:["service_id","name","description","tags"]}},{name:"browse_mcp_store",description:"MCPストア(Portal)からインストール可能なMCP一覧を取得します。",inputSchema:{type:"object",properties:{},required:[]}},{name:"install_from_store",description:"MCP ストアから MCP を取得してこの機体に展開し、env と導入版をサーバに記録します。browse_mcp_store で見つけた mcp_id を指定してください。道具一覧に出るかどうかは権限で決まるので、権限の無い MCP をこれで一覧に出すことはできません(自分で作った MCP・共有された MCP は権限に含まれるため、何もしなくても一覧に出ます)。",inputSchema:{type:"object",properties:{mcp_id:{type:"string",description:"インストールするMCPのID"}},required:["mcp_id"]}},{name:"save_mcp_env",description:"MCPの環境変数(APIキー等)をサーバーに安全に保存します。ローカルには保存されません。次回起動時にサーバーから自動取得されます。解約時はアクセスできなくなります。",inputSchema:{type:"object",properties:{service_id:{type:"string",description:"MCP サービスID(例: heygen, gemini-image)"},env:{type:"object",description:'環境変数のキーと値(例: {"HEYGEN_API_KEY": "sk_xxx"})',additionalProperties:{type:"string"}}},required:["service_id","env"]}}],this._catalogTools,this.childManager.getActiveTools())}applyCatalog(e,t={}){const{catalog:r,cloudProxy:o,warnings:i,needChildForSchema:s}=buildCatalogRegistry(e);this._catalogTools=r,this._cloudProxyTools=o,this._catalogServices=new Map,this._needChildForSchema=new Set(s),this._catalogFromCache=!0===t.fromCache;for(const t of Array.isArray(e)?e:[])t&&t.mcpId&&this._catalogServices.set(t.mcpId,t);let n=0;for(const e of i)"no-input-schema"===e.reason?(n+=e.count,log(`[catalog] "${e.mcpId}" (${e.hostingType||"unknown"}): ${e.count}/${e.total} tools have no inputSchema — 一覧には出す(空 schema)。子を起こして実 schema で上書きする`)):log(`[catalog] "${e.mcpId}" (${e.hostingType||"unknown"}) skipped: ${e.reason}`);return n>0&&log(`[catalog] inputSchema 欠損の合計: ${n} 本 / ${this._needChildForSchema.size} service(一覧には出す。子を起こして実 schema で上書きする)`),log(`[catalog] ${r.size} tools registered from ${this._catalogServices.size} services (cloud_proxy: ${o.size})`),r}registerServiceInCatalog(e){const{catalog:t,cloudProxy:r,warnings:o}=buildCatalogRegistry([e]);for(const[e,r]of t)this._catalogTools.set(e,r);for(const[e,t]of r)this._cloudProxyTools.set(e,t);for(const e of o)log(`[catalog] "${e.mcpId}" (${e.hostingType||"unknown"}) skipped: ${e.reason}`);return e&&e.mcpId&&this._catalogServices.set(e.mcpId,e),t.size}unregisterServiceFromCatalog(e){const t=`${e}__`;let r=0;for(const e of[...this._catalogTools.keys()])e.startsWith(t)&&(this._catalogTools.delete(e),this._cloudProxyTools.delete(e),r++);return r}buildChildService(e,t){const r=path.join(os.homedir(),".claude","mcp-servers",e),o=t.entryPoint||"dist/index.js";return{name:t.name,description:t.description,type:"external",command:t.command||"node",args:t.args&&t.args.length?t.args:[path.join(r,o)],env:t.env||{}}}setupHandlers(){this.server.setRequestHandler(ListToolsRequestSchema,async()=>{const e=this.buildToolList(),t=this.childManager.getActiveServiceIds();return log(`[ListTools] ${e.length} tools (active: ${t.join(", ")||"none"})`),{tools:e}}),this.server.setRequestHandler(CallToolRequestSchema,async e=>{const{name:r,arguments:o}=e.params;log(`[CallTool] ${r}`);const i=resolveToken();if("load_knowledge"===r){const{keyword:e}=o;log("[load_knowledge] called");try{const r=await getPromptFromPortal(e,i,LANGUAGE);if(!r||!r.success){const o=r?.error||t("mcp.knowledgeNotFound",{keyword:e});return{content:[{type:"text",text:`❌ ${t("mcp.portalApiFailed",{error:o})}`}],isError:!0}}const o="ja"!==LANGUAGE?"\n\n[Note] The user's preferred language is English.":"",s=[this.updateNoticeText,buildAutoUpdateNoticeText(this._autoUpdateRecords)].filter(Boolean).map(e=>`\n\n${e}`).join("");return{content:[{type:"text",text:`✅ ${t("mcp.knowledgeLoadSuccess")}\n\n${r.knowledge}${o}\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n${t("mcp.knowledgeApplied")}${s}`}]}}catch(e){return log(`[load_knowledge] Exception: ${e.message}`),{content:[{type:"text",text:`❌ ${t("mcp.knowledgeLoadError",{error:e.message})}`}],isError:!0}}}if("search_mcp"===r){const e=this.checkAuth();if(!e.ok)return{content:[{type:"text",text:`🔒 ${e.error}`}],isError:!0};if(!i)return{content:[{type:"text",text:"❌ 未認証です。MCPカタログの検索にはログインが必要です。"}],isError:!0};let t=[];try{const e=await searchMcpServices(o.query,i);if(!e.success)return{content:[{type:"text",text:`❌ MCPカタログ検索に失敗: ${e.error||"Unknown"}`}],isError:!0};t=(e.data||[]).map(e=>({id:e.mcp_id,service:{name:e.name,description:e.description,tags:[],alwaysOn:e.alwaysOn||!1},isInstalled:e.isInstalled||!1}))}catch(e){return log(`[search_mcp] Server search failed: ${e.message}`),{content:[{type:"text",text:`❌ MCPカタログ検索に失敗: ${e.message}`}],isError:!0}}if(0===t.length)return{content:[{type:"text",text:`🔍 「${o.query}」に一致するサービスはありません。\n\n別のキーワードで試すか、browse_mcp_storeでカタログを確認してください。`}]};let r=`🔍 「${o.query}」の検索結果(${t.length}件)\n\n`;for(const e of t.slice(0,10)){const t=e.id,o=e.service,i=this.childManager.isActive(t),s=!0===o.deactivated,n=e.isInstalled?"":" [未インストール]",a=s?" [一覧から外し中]":"";r+=`${s?"🚫":i?"🟢":"⚪"} **${o.name}**${a}${n} (id: \`${t}\`)\n`,r+=` ${o.description}\n\n`}return r+="一覧に戻す: activate_service | ストアから導入: install_from_store",{content:[{type:"text",text:r}]}}if("activate_service"===r){const e=this.checkAuth();if(!e.ok)return{content:[{type:"text",text:`🔒 ${e.error}`}],isError:!0};const{service_id:t}=o,r=await getGatewayConfig(i);if(!r.success)return{content:[{type:"text",text:`❌ サーバー設定の取得に失敗: ${r.error||"Unknown"}`}],isError:!0};const s=(r.data?.services||[]).find(e=>e.mcpId===t);if(!s)return{content:[{type:"text",text:`❌ サービス "${t}" はあなたの権限の中にありません(権限のある MCP は何もしなくても一覧に出ます)。`}],isError:!0};const n=await setServiceDeactivated(t,!1,i);if(!n.success)return{content:[{type:"text",text:`❌ "${t}" を一覧に戻せませんでした: ${n.error||"Unknown"}`}],isError:!0};log(`[activate] "${t}" deactivated=false (一覧に戻した)`);const a=this.registerServiceInCatalog({...s,deactivated:!1});if(0===a)return{content:[{type:"text",text:`❌ "${t}" には目録にツール定義がありません(tools が空)。`}],isError:!0};if("cloud_proxy"===s.hostingType){log(`[activate] "${t}" (cloud_proxy) → ${a} proxy tools registered`);try{await this.server.notification({method:"notifications/tools/list_changed"})}catch(e){log(`[activate] notification error: ${e.message}`)}return{content:[{type:"text",text:`✅ "${s.name}" を一覧に戻しました(cloud_proxy ツール${a}個)`}]}}if(this.childManager.isActive(t)){try{await this.server.notification({method:"notifications/tools/list_changed"})}catch(e){log(`[activate] notification error: ${e.message}`)}return{content:[{type:"text",text:`✅ "${t}" を一覧に戻しました(子プロセスは既に起動済み)。`}]}}log(`[activate] "${t}" (${s.hostingType}) → ${a} catalog tools restored. Sending list_changed.`);try{await this.server.notification({method:"notifications/tools/list_changed"})}catch(e){log(`[activate] notification error: ${e.message}`)}return{content:[{type:"text",text:`✅ "${s.name}" を一覧に戻しました(ツール${a}個)。最初に呼ばれた時に自動で起動します。`}]}}if("deactivate_service"===r){const{service_id:e}=o;if(!i)return{content:[{type:"text",text:"🔒 未認証です。ログインが必要です。"}],isError:!0};const t=await setServiceDeactivated(e,!0,i);if(!t.success)return{content:[{type:"text",text:`❌ "${e}" を一覧から外せませんでした: ${t.error||"Unknown"}`}],isError:!0};log(`[deactivate] "${e}" deactivated=true (一覧から外した)`);const r=this.unregisterServiceFromCatalog(e);r>0&&log(`[deactivate] "${e}" → ${r} catalog tools removed`),this._catalogServices.delete(e);let s=!1;if(this.childManager.isActive(e)&&(this.childManager.deactivate(e),log(`[deactivate] "${e}" child process stopped`),s=!0),r>0||s)try{await this.server.notification({method:"notifications/tools/list_changed"})}catch(e){log(`[deactivate] notification error: ${e.message}`)}let n=`✅ "${e}" を道具一覧から外しました(deactivated=true)。`;return r>0&&(n+=` ツール${r}個を一覧から削除しました。`),s&&(n+=" 子プロセスを停止しました。"),n+=" 次の接続でも一覧に出ません。権限は変わっていないので activate_service で戻せます。",{content:[{type:"text",text:n}]}}if("restart_service"===r){const{service_id:e}=o,t=this.childManager.children.get(e),r=t?.service;if(!r)return isCloudProxyService(this._cloudProxyTools,e)?{content:[{type:"text",text:`ℹ️ "${e}" は cloud_proxy 方式のため、ローカルの再起動対象ではありません(子プロセスを持ちません)。\nサーバ側のツール更新は deploy で全利用者に反映されるので、再起動は不要です。\nツール一覧を取り直したいだけなら deactivate_service → activate_service を実行してください。`}]}:{content:[{type:"text",text:`❌ "${e}" の子プロセスは現在動いていません。道具を呼べば自動で起動します(restart は起動済みの子にだけ効きます)。`}],isError:!0};let s,n=r;if(i)try{const t=await getGatewayConfig(i);if(t.success){const o=(t.data?.services||[]).find(t=>t.mcpId===e);o&&o.env&&(n={...r,env:o.env},log(`[restart] "${e}" env refreshed from server (keys=${Object.keys(o.env).join(",")||"none"})`))}}catch(e){log(`[restart] env refresh failed (using cached): ${e.message}`)}this.childManager.deactivate(e),log(`[restart] "${e}" stopped`);try{s=await this.childManager.activateExternal(e,n)}catch(t){return log(`[restart] Failed "${e}": ${t.message}`),{content:[{type:"text",text:`❌ "${e}" の再起動に失敗しました: ${t.message}`}],isError:!0}}log(`[restart] "${e}" → ${s.length} tools. Sending list_changed.`);try{await this.server.notification({method:"notifications/tools/list_changed"})}catch(e){log(`[restart] notification error: ${e.message}`)}const a=s.map(e=>e.name).join(", ");return{content:[{type:"text",text:`🔄 "${n.name}" を再起動しました(ツール${s.length}個)\n\nツール: ${a||"(なし)"}`}]}}if("unregister_service"===r){const{service_id:e}=o;if(!i)return{content:[{type:"text",text:"🔒 未認証です。ログインが必要です。"}],isError:!0};this.childManager.isActive(e)&&(this.childManager.deactivate(e),log(`[unregister] "${e}" stopped`));const t=await uninstallMcpService(e,i);if(!t.success)return{content:[{type:"text",text:`❌ "${e}" のサーバー削除に失敗: ${t.error||"Unknown"}`}],isError:!0};log(`[unregister] "${e}" uninstalled from server`);try{await this.server.notification({method:"notifications/tools/list_changed"})}catch(e){log(`[unregister] notification error: ${e.message}`)}return{content:[{type:"text",text:`🗑️ "${e}" を削除しました。プロセスも停止済みです。`}]}}if("register_service"===r){const e=this.checkAuth();if(!e.ok)return{content:[{type:"text",text:`🔒 ${e.error}`}],isError:!0};const{service_id:t,env:r}=o;if(!i)return{content:[{type:"text",text:"🔒 未認証です。ログインが必要です。"}],isError:!0};const s=r||{},n=await installMcpService(t,!1,i,s);return n.success?(log(`[register] "${t}" installed on server`),{content:[{type:"text",text:`✅ サービス "${t}" をサーバーに登録しました。\n\n次のステップ:\n- save_mcp_env で APIキー等を設定\n- 次の接続で道具一覧に出ます(activate は不要です)`}]}):{content:[{type:"text",text:`❌ "${t}" の登録に失敗しました: ${n.error||"Unknown"}\n\n※ MCP はサーバーカタログに登録されている必要があります。browse_mcp_store で確認してください。`}],isError:!0}}if("save_mcp_env"===r){const e=this.checkAuth();if(!e.ok)return{content:[{type:"text",text:`🔒 ${e.error}`}],isError:!0};const{service_id:t,env:r}=o;if(!t||!r||0===Object.keys(r).length)return{content:[{type:"text",text:"❌ service_id と env(キー/値のペア)が必要です"}],isError:!0};log(`[save_mcp_env] ${t}: ${Object.keys(r).join(", ")}`);try{const e=await updateMcpEnv(t,r,i);if(!e.success)return{content:[{type:"text",text:`❌ サーバー保存失敗: ${e.error}`}],isError:!0};const o=Object.keys(r).join(", ");return e.warning?{content:[{type:"text",text:`🔐 環境変数をサーバーに保存しました\n\nサービス: ${t}\n保存キー: ${o}\n\n${e.warning}`}]}:{content:[{type:"text",text:`🔐 環境変数をサーバーに保存しました\n\nサービス: ${t}\n保存キー: ${o}\n\n※ ローカルには保存されません。次回起動時にサーバーから自動取得されます。`}]}}catch(e){return log(`[save_mcp_env] error: ${e.message}`),{content:[{type:"text",text:`❌ ${e.message}`}],isError:!0}}}if("browse_mcp_store"===r){log("[browse_mcp_store]");try{const e=await listAvailableMcps({},i,LANGUAGE);if(!e||!e.success)return{content:[{type:"text",text:`❌ MCPカタログの取得に失敗: ${e?.error||"Unknown"}`}],isError:!0};const t=e.data||[];if(0===t.length)return{content:[{type:"text",text:"📦 インストール可能なMCPはありません。"}]};let r=`📦 MCPストア一覧 (${t.length}件)\n\n`;return t.forEach(e=>{const t=e.isOfficial?" [公式]":"";r+=`**${e.name}**${t}\n`,r+=` ID: ${e.mcpId}\n`,r+=` ${e.description}\n`,r+=` ツール数: ${e.toolCount}\n\n`}),r+='\nインストールするには: install_from_store(mcp_id: "MCP_ID")',{content:[{type:"text",text:r}]}}catch(e){return log(`[browse_mcp_store] error: ${e.message}`),{content:[{type:"text",text:`❌ ${e.message}`}],isError:!0}}}if("install_from_store"===r){const{mcp_id:e}=o;log(`[install_from_store] mcp_id=${e}`);try{const t=await downloadMcpPackage(e,i);if(!t||!t.success)return{content:[{type:"text",text:`❌ MCPダウンロードに失敗: ${t?.error||"Unknown"}`}],isError:!0};const r=t.data,o=r.packageSource||{},s=r.files||[];let n=o.hostingType||o.hosting&&o.hosting.type||null;if(i){let t=!1;try{const r=await getGatewayConfig(i);if(r.success){const o=(r.data?.services||[]).find(t=>t.mcpId===e);o&&(t=!0===o.alwaysOn,n||(n=o.hostingType))}}catch(e){}const r=await installMcpService(e,t,i);if(!r.success)return{content:[{type:"text",text:`❌ サーバー登録失敗: ${r.error||"Unknown"}`}],isError:!0};log(`[install_from_store] Server sync OK: ${e} (alwaysOn=${t})`)}if("cloud_proxy"===n){log(`[install_from_store] "${e}" is cloud_proxy, skipping local extract`);let t=`✅ MCP「${o.name||e}」をインストールしました(cloud_proxy)\n\n`;return t+="☁ クラウド実行のためローカル展開は不要です\n",o.installNotes&&(t+=`\n📝 ${o.installNotes}\n`),t+="\n権限に含まれていれば、次の接続で道具一覧に出ます(activate_service を撃つ必要はありません)。",{content:[{type:"text",text:t}]}}const a=path.join(os.homedir(),".claude","mcp-servers",e),c=await extractDownloadedPackage({mcpId:e,installDir:a,pkg:r});if("empty"===c.stage)return{content:[{type:"text",text:"❌ MCPパッケージにファイルが含まれていません。"}],isError:!0};if(!c.ok)return log(`[install_from_store] ${e} failed at ${c.stage}: ${c.error.message}`),{content:[{type:"text",text:formatInstallFailure(o.name||e,c)}],isError:!0};log(`[install_from_store] ${s.length} files written to ${a}`);let l=`✅ MCP「${o.name||e}」をインストールしました\n\n`;l+=`📁 インストール先: ${a}\n`,l+=`📄 ファイル数: ${s.length}\n`,o.installNotes&&(l+=`\n📝 ${o.installNotes}\n`);const d=(o.requiredEnvVars||[]).filter(e=>!process.env[e]);return d.length>0&&(l+="\n⚠️ 以下の環境変数を save_mcp_env で設定してください:\n",d.forEach(e=>{l+=` - ${e}\n`})),l+="\n権限に含まれていれば、次の接続で道具一覧に出ます(activate_service を撃つ必要はありません)。",{content:[{type:"text",text:l}]}}catch(e){return log(`[install_from_store] error: ${e.message}`),{content:[{type:"text",text:`❌ ${e.message}`}],isError:!0}}}if(this._cloudProxyTools&&this._cloudProxyTools.has(r)){const e=this._cloudProxyTools.get(r);log(`[callTool] Cloud proxy: ${r} → ${e.mcpId}/${e.toolName}`);try{const t=await callMcpToolProxy(e.mcpId,e.toolName,o,i);return t.success&&t.data?t.data.content?t.data:{content:[{type:"text",text:JSON.stringify(t.data,null,2)}]}:{content:[{type:"text",text:`❌ プロキシエラー: ${t.error||"Unknown"}`}],isError:!0}}catch(e){return log(`[callTool] Cloud proxy error "${r}": ${e.message}`),{content:[{type:"text",text:`❌ クラウドプロキシエラー: ${e.message}`}],isError:!0}}}{const e=(this._catalogTools.get(r)||{}).mcpId||String(r).split("__")[0];if(this._childSettling.has(e)&&!await this.waitForChildSettled(e,r))return{content:[{type:"text",text:CHILD_NOT_READY_TEXT}],isError:!0}}try{const{found:e,result:t}=await this.childManager.callTool(r,o);if(e)return t&&t.content?t:{content:[{type:"text",text:String(t)}]}}catch(e){return log(`[callTool] Error proxying "${r}": ${e.message}`),{content:[{type:"text",text:`❌ ツール実行エラー: ${e.message}`}],isError:!0}}const s=this._catalogTools.get(r);if(s&&"cloud_proxy"!==s.hostingType){const e=s.mcpId;this._catalogFromCache&&this._configRefresh&&(log(`[callTool] "${e}" は目録キャッシュ由来。起動仕様の到着を待つ。`),await this._configRefresh),this.startChildOnDemand(e);const t=await this.childManager.waitForReady(e,3e4);if(!t.ready){if("failed"===t.reason){const r=t.error?.message||String(t.error||"Unknown");return log(`[callTool] "${e}" failed to start: ${r}`),{content:[{type:"text",text:`❌ "${e}" の起動に失敗しました: ${r}`}],isError:!0}}return"timeout"===t.reason?(log(`[callTool] "${e}" not ready within 30000ms for "${r}".`),{content:[{type:"text",text:CHILD_NOT_READY_TEXT}],isError:!0}):(log(`[callTool] "${e}" could not be started for "${r}" (reason=${t.reason}).`),{content:[{type:"text",text:`❌ "${e}" を起動できませんでした(設定が見つかりません)。`}],isError:!0})}if(!await this.waitForChildSettled(e,r))return{content:[{type:"text",text:CHILD_NOT_READY_TEXT}],isError:!0};try{const{found:t,result:i}=await this.childManager.callTool(r,o);if(t)return i&&i.content?i:{content:[{type:"text",text:String(i)}]};log(`[callTool] "${r}" is in catalog but child "${e}" does not have it.`)}catch(e){return log(`[callTool] Error proxying "${r}" after ready: ${e.message}`),{content:[{type:"text",text:`❌ ツール実行エラー: ${e.message}`}],isError:!0}}}return{content:[{type:"text",text:`❌ Unknown tool: ${r}`}],isError:!0}})}startChildrenForMissingSchema(){let e=0;for(const t of this._needChildForSchema){const r=this._catalogServices.get(t);if(r)if("cloud_proxy"!==r.hostingType){if(!this.childManager.isActive(t)&&!this.childManager.isStarting(t)){log(`[schemaChild] "${t}" (${r.hostingType}) を起こして実 schema を取りに行く`);try{this.startChildOnDemand(t),e++}catch(e){log(`[schemaChild] "${t}" の起動に失敗: ${e.message}(⛔ 席は落とさない)`)}}}else log(`[schemaChild] "${t}" は cloud_proxy のため子を起こせない。schema 欠損の道具は一覧に出ない。`)}return log(`[schemaChild] ${e} service(=目録に schema が無い道具を持つ service の数)`),e}async loadCatalog(e){if(!e)return log("[catalog] No token, starting with no catalog tools."),null;let t=[];try{const r=await getGatewayConfig(e);if(!r.success)return log(`[catalog] Server config failed: ${r.error||"Unknown"}. Starting with no services.`),null;t=r.data?.services||[],log(`[catalog] Server config: ${t.length} services`),this.applyCatalog(t)}catch(e){return log(`[catalog] Server config error: ${e.message}. Starting with no services.`),null}try{const e=collectUpdateNotices(t);this.updateNoticeText=buildUpdateNoticeText(e);for(const t of e)"not-applicable"!==t.status&&log(`[versionCheck] ${t.mcpId}: ${t.status} (${t.reason}) catalog=${t.catalogVersion} local=${t.localVersion}`)}catch(e){log(`[versionCheck] skipped: ${e.message}`)}return t}startChildOnDemand(e){const t=this._catalogServices.get(e);if(!t||!0===t.deactivated)return null;if("cloud_proxy"===t.hostingType)return null;if(this.childManager.isActive(e))return null;const r=this.childManager.isStarting(e),o=this.childManager.beginActivateExternal(e,this.buildChildService(e,t));if(r||log(`[startChild] "${e}" (${t.hostingType}) starting on demand...`),!this._childSettling.has(e)){const t=o.then(t=>this.reconcileChildWithCatalog(e,t)).catch(t=>log(`[startChild] "${e}" post-start error: ${t.message}`)).finally(()=>{this._childSettling.get(e)===t&&this._childSettling.delete(e)});this._childSettling.set(e,t)}return o}async waitForChildSettled(e,t){const r=this._childSettling.get(e);if(!r)return!0;let o=null;const i=new Promise(e=>{o=setTimeout(()=>e(!1),3e4),"function"==typeof o.unref&&o.unref()});try{const o=await Promise.race([r.then(()=>!0),i]);return o||log(`[callTool] "${e}" の突き合わせ(自動更新を含む)が 30000ms で済まない → "${t}" は転送しない`),o}finally{o&&clearTimeout(o)}}async reconcileChildWithCatalog(e,t,r={}){const o=decideCatalogReconciliation(this._catalogTools,e,t);if(this._autoUpdating.has(e)&&!r.fromAutoUpdate)return log(`[autoUpdate] "${e}" は更新中 → この突き合わせは見送る`),o;if(!r.fromAutoUpdate){const r=this.evaluateVersionOnDisk(e);if(shouldAutoUpdate({decision:o,notice:r,alreadyTried:this._autoUpdateTried.has(e)}).update){this._autoUpdateTried.add(e);const i=this.autoUpdateAndRestart(e,t,o,r);this._autoUpdating.set(e,i);try{return await i}finally{this._autoUpdating.delete(e)}}}if(!o.ready){const r=t&&t.error?`: ${t.error.message||t.error}`:"";return log(`[versionDrift] "${e}" not ready (${o.reason})${r} → 剪定も通知もしない`),o}if(!o.notify)return log(`[versionDrift] "${e}" matches catalog (${t.tools.length} tools) → no list_changed`),o;for(const e of o.prune)this._catalogTools.delete(e),this._cloudProxyTools.delete(e);const i=o.diff;log(`[versionDrift] "${e}" differs from catalog: +${i.added.length} -${i.removed.length} ~${i.changed.length} → list_changed`);try{await this.server.notification({method:"notifications/tools/list_changed"})}catch(e){log(`[versionDrift] notification error: ${e.message}`)}return o}evaluateVersionOnDisk(e){const t=this._catalogServices.get(e);return t?evaluateUpdateNotice({mcpId:e,hostingType:t.hostingType,catalogVersion:t.packageVersion,localVersion:readLocalPackageVersion(e,{entryPoint:t.entryPoint})}):null}async autoUpdateAndRestart(e,t,r,o){const i=this._catalogServices.get(e),s=path.join(os.homedir(),".claude","mcp-servers"),n=r.prune.length;log(`[autoUpdate] "${e}" disk=${o.localVersion} catalog=${o.catalogVersion} で ${n} 本が剪定される → 目録の版へ上げる`);const a=await updateMcpOnDisk({mcpId:e,installRoot:s,catalogVersion:o.catalogVersion,entryPoint:i&&i.entryPoint,readLocalVersion:()=>readLocalPackageVersion(e,{installRoot:s,entryPoint:i&&i.entryPoint}),download:()=>downloadMcpPackage(e,resolveToken()),extract:(t,r)=>extractDownloadedPackage({mcpId:e,installDir:t,pkg:r})});if(!a.ok)return log(`[autoUpdate] "${e}" 上げられなかった(${a.reason})→ 今の版のまま剪定する`),this.reconcileChildWithCatalog(e,t,{fromAutoUpdate:!0});this.childManager.deactivate(e);const c=await this.childManager.beginActivateExternal(e,this.buildChildService(e,i));return c.ok?(log(`[autoUpdate] ${e} ${a.from} → ${a.to}(剪定されるはずだった口: ${n} 本)${"other"===a.by?"・同じ機体の別の席が上げた版を使う":""}`),this._autoUpdateRecords.push({mcpId:e,from:a.from,to:a.to,prunedWouldBe:n}),this.reconcileChildWithCatalog(e,c,{fromAutoUpdate:!0})):(log(`[autoUpdate] "${e}" ${a.from} → ${a.to} の後、子が起きなかった: ${c.error&&c.error.message}`),this.reconcileChildWithCatalog(e,c,{fromAutoUpdate:!0}))}persistCatalogCache(e,t){return!!e&&writeCatalogCache(CATALOG_CACHE_FILE,e,catalogCacheFingerprint(t),log)}toolListSignature(){return stableJson(this.buildToolList().map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema})))}async refreshCatalogInBackground(e){const t=this.toolListSignature();let r;try{r=await this.loadCatalog(e)}catch(e){return log(`[catalogRefresh] failed, keeping cached catalog: ${e.message}`),{notified:!1,reason:"failed"}}if(t===this.toolListSignature())return log("[catalogRefresh] server catalog matches cache → no list_changed"),this.persistCatalogCache(r,e),{notified:!1,reason:"same"};log("[catalogRefresh] server catalog differs from cache → list_changed");try{await this.server.notification({method:"notifications/tools/list_changed"})}catch(e){log(`[catalogRefresh] notification error: ${e.message}`)}return this.persistCatalogCache(r,e),{notified:!0,reason:"diff"}}async run(){const e=resolveToken(),t=catalogCacheFingerprint(e),r=readCatalogCache(CATALOG_CACHE_FILE,t,log);let o=null;r?(this.applyCatalog(r,{fromCache:!0}),log(`[catalogCache] ${this._catalogTools.size} tools from cache (HTTP は待たない)`)):(log("[catalogCache] no usable cache, waiting for server config"),o=await this.loadCatalog(e));const i=new StdioServerTransport;await this.server.connect(i),log(`[Gateway] BlueLamp Gateway v2.0.0 started. (${this._catalogTools.size} catalog tools available at connect)`),this.persistCatalogCache(o,e),r?(this._configRefresh=this.refreshCatalogInBackground(e).catch(e=>(log(`[catalogRefresh] unexpected: ${e.message}`),{notified:!1,reason:"failed"})),this._configRefresh.then(()=>this.startChildrenForMissingSchema()).catch(e=>log(`[schemaChild] deferred start failed: ${e.message}`))):this.startChildrenForMissingSchema();const s=resolveToken();if(KEYWORD&&s){log("[Gateway] Auto-loading knowledge");const e=await getPromptFromPortal(KEYWORD,s,LANGUAGE);e&&e.success?log(`[Gateway] Auto-load successful: ${e.title}`):log("[Gateway] Auto-load failed")}}}function buildCatalogRegistry(e){const t=new Map,r=new Map,o=[],i=[];for(const s of Array.isArray(e)?e:[]){if(!s||"string"!=typeof s.mcpId||!s.mcpId)continue;const e=s.hostingType||null;if(!0===s.deactivated)continue;const n=Array.isArray(s.tools)?s.tools:[];if(0===n.length){o.push({mcpId:s.mcpId,hostingType:e,reason:"no-tools"});continue}const a=[];for(const i of n){if(!i||"string"!=typeof i.name||!i.name){o.push({mcpId:s.mcpId,hostingType:e,reason:"unnamed-tool"});continue}i.inputSchema&&"object"==typeof i.inputSchema||a.push(i.name);const n=`${s.mcpId}__${i.name}`,c={name:n,mcpId:s.mcpId,toolName:i.name,hostingType:e,description:i.description,inputSchema:i.inputSchema};t.set(n,c),"cloud_proxy"===e&&r.set(n,{mcpId:s.mcpId,toolName:i.name,description:i.description,inputSchema:i.inputSchema})}a.length>0&&(o.push({mcpId:s.mcpId,hostingType:e,reason:"no-input-schema",count:a.length,total:n.length,tools:a}),i.push(s.mcpId))}return{catalog:t,cloudProxy:r,warnings:o,needChildForSchema:i}}function catalogEntryToTool(e){return{name:e.name,description:e.description||`[${e.mcpId}] ${e.toolName}`,inputSchema:e.inputSchema||{type:"object",properties:{}}}}function buildGatewayToolList(e,t,r){const o=new Map;for(const t of Array.isArray(e)?e:[])t&&t.name&&o.set(t.name,t);if(t&&"function"==typeof t.values)for(const e of t.values())o.has(e.name)||o.set(e.name,catalogEntryToTool(e));for(const e of Array.isArray(r)?r:[])e&&e.name&&o.set(e.name,e);return[...o.values()]}function sanitizeServicesForCache(e){return(Array.isArray(e)?e:[]).filter(e=>e&&"string"==typeof e.mcpId&&e.mcpId).map(e=>({mcpId:e.mcpId,name:e.name,description:e.description,hostingType:e.hostingType||null,deactivated:!0===e.deactivated,tools:(Array.isArray(e.tools)?e.tools:[]).filter(e=>e&&"string"==typeof e.name&&e.name).map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema}))}))}function catalogCacheFingerprint(e){return e?require("crypto").createHash("sha256").update(String(e)).digest("hex").slice(0,16):null}function sliceTailPreservingSurrogates(e,t){const r=String(null==e?"":e);if(r.length<=t)return r;const o=r.slice(-t),i=o.charCodeAt(0);return i>=56320&&i<=57343?o.slice(1):o}function stableJson(e){return void 0===e?"null":null===e||"object"!=typeof e?JSON.stringify(e):Array.isArray(e)?`[${e.map(stableJson).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${stableJson(e[t])}`).join(",")}}`}function diffChildToolsAgainstCatalog(e,t,r){const o=`${t}__`,i=new Set;if(e&&"function"==typeof e.keys)for(const t of e.keys())"string"==typeof t&&t.startsWith(o)&&i.add(t);const s=[],n=[],a=new Set;for(const t of Array.isArray(r)?r:[]){if(!t||!t.name)continue;a.add(t.name);const r=e&&"function"==typeof e.get?e.get(t.name):void 0;r?stableJson(r.description)===stableJson(t.description)&&stableJson(r.inputSchema)===stableJson(t.inputSchema)||n.push(t.name):s.push(t.name)}const c=[...i].filter(e=>!a.has(e));return{added:s,removed:c,changed:n,hasDiff:s.length+c.length+n.length>0}}function decideCatalogReconciliation(e,t,r){if(!r||!0!==r.ok||!Array.isArray(r.tools))return{ready:!1,prune:[],notify:!1,reason:r&&r.reason||"not-ready",diff:null};const o=diffChildToolsAgainstCatalog(e,t,r.tools);return{ready:!0,prune:o.removed,notify:o.hasDiff,reason:"ready",diff:o}}function readCatalogCache(e,t,r){const o=r||(()=>{});if(!t)return null;let i,s;try{i=fs.readFileSync(e,"utf8")}catch(e){return"ENOENT"!==e.code&&o(`[catalogCache] read failed: ${e.message}`),null}try{s=JSON.parse(i)}catch(e){return o(`[catalogCache] broken JSON, ignoring: ${e.message}`),null}return s&&1===s.version?s.tokenFingerprint!==t?(o("[catalogCache] fingerprint mismatch (口座が違う), ignoring"),null):Array.isArray(s.services)?s.services:(o("[catalogCache] services が配列でない, ignoring"),null):(o(`[catalogCache] version mismatch (${s&&s.version}), ignoring`),null)}function writeCatalogCache(e,t,r,o){const i=o||(()=>{});if(!r)return!1;try{fs.mkdirSync(path.dirname(e),{recursive:!0});const o={version:1,tokenFingerprint:r,savedAt:(new Date).toISOString(),services:sanitizeServicesForCache(t)},i=`${e}.${process.pid}.tmp`;return fs.writeFileSync(i,JSON.stringify(o),{mode:384}),fs.renameSync(i,e),!0}catch(e){return i(`[catalogCache] write failed: ${e.message}`),!1}}function isCloudProxyService(e,t){if(!e||"function"!=typeof e.keys)return!1;const r=`${t}__`;for(const t of e.keys())if("string"==typeof t&&t.startsWith(r))return!0;return!1}if(module.exports={ChildMcpProcess:ChildMcpProcess,ChildMcpManager:ChildMcpManager,BlueLampServer:BlueLampServer,isCloudProxyService:isCloudProxyService,buildCatalogRegistry:buildCatalogRegistry,buildGatewayToolList:buildGatewayToolList,catalogEntryToTool:catalogEntryToTool,diffChildToolsAgainstCatalog:diffChildToolsAgainstCatalog,decideCatalogReconciliation:decideCatalogReconciliation,sanitizeServicesForCache:sanitizeServicesForCache,catalogCacheFingerprint:catalogCacheFingerprint,readCatalogCache:readCatalogCache,writeCatalogCache:writeCatalogCache,CATALOG_CACHE_FILE:CATALOG_CACHE_FILE,CATALOG_CACHE_VERSION:1,stableJson:stableJson,sliceTailPreservingSurrogates:sliceTailPreservingSurrogates,CHILD_READY_TIMEOUT_MS:3e4,CHILD_NOT_READY_TEXT:CHILD_NOT_READY_TEXT},require.main===module){const e=new BlueLampServer;let t=!1;const r=r=>{if(!t){t=!0;try{log(`[Gateway] Shutdown (${r}) - cleaning up children...`)}catch(e){}if(e&&e.childManager&&e.childManager.children)for(const[t,r]of e.childManager.children)try{try{log(`[Gateway] Stopping child: ${t}`)}catch(e){}r&&"external"===r.type&&r.process&&"function"==typeof r.process.stop&&r.process.stop()}catch(e){}setTimeout(()=>process.exit(0),200).unref()}};process.on("SIGTERM",()=>r("SIGTERM")),process.on("SIGINT",()=>r("SIGINT")),process.on("SIGHUP",()=>r("SIGHUP")),process.stdin.on("end",()=>r("stdin-end")),process.stdin.on("close",()=>r("stdin-close")),process.on("exit",()=>{if(e&&e.childManager&&e.childManager.children)for(const[t,r]of e.childManager.children)try{r&&r.process&&r.process.process&&"function"==typeof r.process.process.kill&&r.process.process.kill("SIGKILL")}catch(e){}}),e.run().catch(e=>{log(`[Gateway] Fatal: ${e.message}`),process.exit(1)})}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const fetch=(...t)=>import("node-fetch").then(({default:e})=>e(...t)),https=require("https"),fs=require("fs"),path=require("path"),os=require("os"),{requireFromPackage:requireFromPackage}=require("../requireFromPackage.cjs"),{logger:logger}=requireFromPackage(require,"../../utils/logger"),{t:t}=requireFromPackage(require,"../../i18n"),PORTAL_URL_ENV=process.env.BLUELAMP_PORTAL_API_BASE_URL||process.env.PORTAL_URL||"",isDevEnvironment=PORTAL_URL_ENV.includes("localhost"),httpsAgent=new https.Agent({rejectUnauthorized:!isDevEnvironment}),PORTAL_URL=PORTAL_URL_ENV||(isDevEnvironment?"http://localhost:8430/api/bluelamp":"https://api.motohi.jp/api/bluelamp"),LOG_DIR=path.join(os.homedir(),".bluelamp-vscode","logs"),LOG_FILE=path.join(LOG_DIR,"mcp.log");function log(t){const e=`[${(new Date).toISOString()}] ${t}\n`;fs.appendFileSync(LOG_FILE,e),logger.debug(t)}function activeTenantHeaders(){const t=process.env.MUSUHI_TENANT_ID||"";return t?{"X-Tenant-ID":t}:{}}let _cliVersion;function getCliVersion(){if(void 0!==_cliVersion)return _cliVersion;let t=__dirname;for(let e=0;e<6;e++){try{const e=require(path.join(t,"package.json"));if(e&&e.version&&e.bin&&Object.keys(e.bin).some(t=>/^[a-z]+\d+$/.test(t)))return _cliVersion=e.version,_cliVersion}catch(t){}const e=path.dirname(t);if(e===t)break;t=e}return _cliVersion=null,_cliVersion}async function getPromptFromPortal(e,r,o="ja"){try{if(log(`[portal-api-client] getPromptFromPortal called with keyword: ${e}, lang: ${o}, token: ${r?"present":"missing"}`),!r)return log("[portal-api-client] No authentication token provided"),{success:!1,error:t("mcp.noAuthToken")};const s=activeTenantHeaders()["X-Tenant-ID"],a=encodeURIComponent(e);let n=`${PORTAL_URL}/cli/prompts/knowledge-injection/${a}?lang=${o}`;s&&(n+=`&tenant_id=${encodeURIComponent(s)}`),log(`[portal-api-client] Direct keyword search: ${n}`),log("[portal-api-client] About to call fetch...");const c=await fetch(n,{method:"GET",headers:{"X-CLI-Token":r,...getCliVersion()?{"X-CLI-Version":getCliVersion()}:{},...activeTenantHeaders(),"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:n.startsWith("https")?httpsAgent:void 0});if(log("[portal-api-client] Fetch completed"),log(`[portal-api-client] Response status: ${c.status}`),log(`[portal-api-client] Response headers: ${JSON.stringify(Object.fromEntries(c.headers.entries()))}`),!c.ok){log(`[portal-api-client] Portal API error: ${c.status}`);const e=await c.text();log(`[portal-api-client] Error response: ${e}`);let r=t("mcp.portalApiError",{status:c.status}),o=null;try{const t=JSON.parse(e);t.message&&(r=t.message),t.code&&(o=t.code)}catch(t){}return{success:!1,error:r,status:c.status,code:o}}const i=await c.json();if(log("[portal-api-client] Direct keyword search completed successfully"),!i.success)return log("[portal-api-client] API returned success: false"),{success:!1,error:i.message||t("mcp.apiReturnedError")};const l=i.data;if(!l)return log(`[portal-api-client] No prompt found for keyword: ${e}`),{success:!1,error:t("mcp.promptNotFoundForKeyword",{keyword:e})};if(log(`[portal-api-client] Found prompt: ${l.title}`),l.content||l.text)return{success:!0,knowledge:l.content||l.text,title:l.title,tags:l.tags||[]};try{const t=`${PORTAL_URL}/cli/prompts/${l.id}`;log(`[portal-api-client] Fetching prompt details from: ${t}`);const e=await fetch(t,{method:"GET",headers:{"X-CLI-Token":r,"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:httpsAgent});if(e.ok){const t=await e.json();if(t.success&&t.data?.prompt?.content)return log("[portal-api-client] Successfully fetched prompt content"),{success:!0,knowledge:t.data.prompt.content,title:l.title||l.name,tags:l.tags}}}catch(t){log(`[portal-api-client] Error fetching prompt details: ${t.message}`)}return{success:!0,knowledge:l.description||`# ${l.title}\n\n${t("mcp.knowledgeLoadError",{error:"detail fetch failed"})}`,title:l.title||l.name,tags:l.tags}}catch(e){return log(`[portal-api-client] FATAL ERROR in getPromptFromPortal: ${e.message}`),log(`[portal-api-client] Error stack: ${e.stack}`),logger.error(`Failed to get prompt from Portal: ${e.message}`),{success:!1,error:t("mcp.portalCommunicationError",{error:e.message}),networkFailure:Boolean(e&&"FetchError"===e.name)}}}async function getSlotConfig(t,e){try{if(!e)return log("[portal-api-client] getSlotConfig: No token"),{ok:!1,reason:"no-token"};const r=activeTenantHeaders()["X-Tenant-ID"],o=`${PORTAL_URL}/cli/slot-config/${t}`;log(`[portal-api-client] Fetching slot config: ${o}${r?` (tenant=${r})`:""}`);const s=await fetch(o,{method:"GET",headers:{"X-CLI-Token":e,...getCliVersion()?{"X-CLI-Version":getCliVersion()}:{},...activeTenantHeaders(),"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:o.startsWith("https")?httpsAgent:void 0});if(!s.ok){log(`[portal-api-client] Slot config API error: ${s.status}`);let t=null;try{const e=await s.json();t=e?.error?.message||e?.message||null}catch{t=null}return 404===s.status?{ok:!1,reason:"not-configured",status:404,message:t}:403===s.status?{ok:!1,reason:"rank",status:403,message:t}:{ok:!1,reason:"http",status:s.status,message:t}}const a=await s.json();return a.success&&a.data?.keyword?(log(`[portal-api-client] Slot ${t}: custom keyword "${a.data.keyword}"`),{ok:!0,keyword:a.data.keyword}):(log(`[portal-api-client] Slot ${t}: no custom config`),{ok:!0,keyword:null})}catch(t){return log(`[portal-api-client] getSlotConfig error: ${t.message}`),{ok:!1,reason:"network",status:null,message:t.message}}}async function reportViolation(e,r,o,s){try{if(log(`[portal-api-client] reportViolation called: severity=${r}`),!o)return{success:!1,error:t("mcp.violationNoToken")};const a=`${PORTAL_URL}/cli/report-violation`,n={reason:e,severity:r};s&&(n.userMessage=s);const c=await fetch(a,{method:"POST",headers:{"X-CLI-Token":o,"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:a.startsWith("https")?httpsAgent:void 0,body:JSON.stringify(n)});if(!c.ok){const e=await c.text();return log(`[portal-api-client] reportViolation error: ${c.status} ${e}`),{success:!1,error:t("mcp.violationApiError",{status:c.status})}}const i=await c.json();return log(`[portal-api-client] reportViolation result: action=${i.action}, count=${i.violationCount}`),i}catch(e){return log(`[portal-api-client] reportViolation FATAL: ${e.message}`),{success:!1,error:t("mcp.violationCommunicationError",{error:e.message})}}}async function listAvailableMcps(e={},r,o="ja"){try{if(log(`[portal-api-client] listAvailableMcps called: ${JSON.stringify(e)}`),!r)return{success:!1,error:t("mcp.noAuthToken")};const s=new URLSearchParams;e.search&&s.set("search",e.search),e.limit&&s.set("limit",String(e.limit)),s.set("lang",o);const a=`${PORTAL_URL}/mcp/catalog?${s.toString()}`;log(`[portal-api-client] Fetching MCP catalog: ${a}`);const n=await fetch(a,{method:"GET",headers:{"X-CLI-Token":r,"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:a.startsWith("https")?httpsAgent:void 0});if(!n.ok){const e=await n.text();log(`[portal-api-client] listAvailableMcps error: ${n.status} ${e}`);let r=t("mcp.listMcpsFailed",{error:`HTTP ${n.status}`});try{const t=JSON.parse(e);t.message&&(r=t.message)}catch(t){}return{success:!1,error:r}}const c=await n.json();return log(`[portal-api-client] listAvailableMcps: ${c.data?.length||0} MCPs found`),{success:!0,data:c.data||[]}}catch(e){return log(`[portal-api-client] listAvailableMcps FATAL: ${e.message}`),{success:!1,error:t("mcp.portalCommunicationError",{error:e.message})}}}async function getMcpInfo(e,r,o="ja"){try{if(log(`[portal-api-client] getMcpInfo called: mcpId=${e}`),!r)return{success:!1,error:t("mcp.noAuthToken")};const s=`${PORTAL_URL}/mcp/${encodeURIComponent(e)}/details?lang=${o}`;log(`[portal-api-client] Fetching MCP info: ${s}`);const a=await fetch(s,{method:"GET",headers:{"X-CLI-Token":r,"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:s.startsWith("https")?httpsAgent:void 0});if(!a.ok){const e=await a.text();log(`[portal-api-client] getMcpInfo error: ${a.status} ${e}`);let r=t("mcp.getMcpInfoFailed",{error:`HTTP ${a.status}`});try{const t=JSON.parse(e);t.message&&(r=t.message)}catch(t){}return{success:!1,error:r}}const n=await a.json();return log(`[portal-api-client] getMcpInfo: found ${n.data?.name||e}`),{success:!0,data:n.data}}catch(e){return log(`[portal-api-client] getMcpInfo FATAL: ${e.message}`),{success:!1,error:t("mcp.portalCommunicationError",{error:e.message})}}}async function callMcpTool(e,r,o,s){try{if(log(`[portal-api-client] callMcpTool called: mcpId=${e}, tool=${r}`),!s)return{success:!1,error:t("mcp.noAuthToken")};const a=`${PORTAL_URL}/mcp/${encodeURIComponent(e)}/call`,n={tool_name:r,arguments:o};log(`[portal-api-client] Calling MCP tool: ${a}`);const c=await fetch(a,{method:"POST",headers:{"X-CLI-Token":s,...activeTenantHeaders(),"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:a.startsWith("https")?httpsAgent:void 0,body:JSON.stringify(n)});if(!c.ok){const e=await c.text();log(`[portal-api-client] callMcpTool error: ${c.status} ${e}`);let r=t("mcp.callToolFailed",{error:`HTTP ${c.status}`});try{const t=JSON.parse(e);t.message&&(r=t.message)}catch(t){}return{success:!1,error:r}}const i=await c.json();return log("[portal-api-client] callMcpTool: success"),{success:!0,data:i.data}}catch(e){return log(`[portal-api-client] callMcpTool FATAL: ${e.message}`),{success:!1,error:t("mcp.portalCommunicationError",{error:e.message})}}}async function scanMcpCode(e,r){try{if(log("[portal-api-client] scanMcpCode called"),!r)return{success:!1,error:t("mcp.noAuthToken")};const o=`${PORTAL_URL}/mcp/scan`,s=await fetch(o,{method:"POST",headers:{"X-CLI-Token":r,"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:o.startsWith("https")?httpsAgent:void 0,body:JSON.stringify({code:e})});if(!s.ok){const t=await s.text();return log(`[portal-api-client] scanMcpCode error: ${s.status} ${t}`),{success:!1,error:`HTTP ${s.status}`}}return{success:!0,data:(await s.json()).data}}catch(e){return log(`[portal-api-client] scanMcpCode FATAL: ${e.message}`),{success:!1,error:t("mcp.portalCommunicationError",{error:e.message})}}}async function deployUserMcp(e,r){try{if(log(`[portal-api-client] deployUserMcp called: name=${e.name}`),!r)return{success:!1,error:t("mcp.noAuthToken")};const o=`${PORTAL_URL}/mcp/deploy`,s=await fetch(o,{method:"POST",headers:{"X-CLI-Token":r,"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:o.startsWith("https")?httpsAgent:void 0,body:JSON.stringify(e)});if(!s.ok){const t=await s.text();log(`[portal-api-client] deployUserMcp error: ${s.status} ${t}`);let e=`HTTP ${s.status}`;try{const r=JSON.parse(t);if(r.error&&(e=r.error),r.details)return{success:!1,error:e,details:r.details}}catch(t){}return{success:!1,error:e}}return{success:!0,data:(await s.json()).data}}catch(e){return log(`[portal-api-client] deployUserMcp FATAL: ${e.message}`),{success:!1,error:t("mcp.portalCommunicationError",{error:e.message})}}}async function listUserCreatedMcps(e){try{if(log("[portal-api-client] listUserCreatedMcps called"),!e)return{success:!1,error:t("mcp.noAuthToken")};const r=`${PORTAL_URL}/mcp/user/me/created`,o=await fetch(r,{method:"GET",headers:{"X-CLI-Token":e,"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:r.startsWith("https")?httpsAgent:void 0});return o.ok?{success:!0,data:(await o.json()).data}:(await o.text(),log(`[portal-api-client] listUserCreatedMcps error: ${o.status}`),{success:!1,error:`HTTP ${o.status}`})}catch(e){return log(`[portal-api-client] listUserCreatedMcps FATAL: ${e.message}`),{success:!1,error:t("mcp.portalCommunicationError",{error:e.message})}}}async function deleteUserMcp(e,r){try{if(log(`[portal-api-client] deleteUserMcp called: mcpId=${e}`),!r)return{success:!1,error:t("mcp.noAuthToken")};const o=`${PORTAL_URL}/mcp/${encodeURIComponent(e)}`,s=await fetch(o,{method:"DELETE",headers:{"X-CLI-Token":r,"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:o.startsWith("https")?httpsAgent:void 0});if(!s.ok){const t=await s.text();log(`[portal-api-client] deleteUserMcp error: ${s.status}`);let e=`HTTP ${s.status}`;try{const r=JSON.parse(t);r.error&&(e=r.error)}catch(t){}return{success:!1,error:e}}return{success:!0,data:(await s.json()).data}}catch(e){return log(`[portal-api-client] deleteUserMcp FATAL: ${e.message}`),{success:!1,error:t("mcp.portalCommunicationError",{error:e.message})}}}async function listMyPrompts(e){try{if(log("[portal-api-client] listMyPrompts called"),!e)return{success:!1,error:t("mcp.noAuthToken")};const r=`${PORTAL_URL}/cli/my-agents`,o=await fetch(r,{method:"GET",headers:{"X-CLI-Token":e,"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:r.startsWith("https")?httpsAgent:void 0});return o.ok?{success:!0,data:(await o.json()).data||[]}:(await o.text(),log(`[portal-api-client] listMyPrompts error: ${o.status}`),{success:!1,error:`HTTP ${o.status}`})}catch(e){return log(`[portal-api-client] listMyPrompts FATAL: ${e.message}`),{success:!1,error:t("mcp.portalCommunicationError",{error:e.message})}}}async function saveMyPrompt(e,r){try{if(log(`[portal-api-client] saveMyPrompt called: title=${e.title}`),!r)return{success:!1,error:t("mcp.noAuthToken")};const o=`${PORTAL_URL}/cli/my-agents`,s=await fetch(o,{method:"POST",headers:{"X-CLI-Token":r,"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:o.startsWith("https")?httpsAgent:void 0,body:JSON.stringify(e)});if(!s.ok){const t=await s.text();log(`[portal-api-client] saveMyPrompt error: ${s.status} ${t}`);let e=`HTTP ${s.status}`;try{const r=JSON.parse(t);r.message&&(e=r.message)}catch(t){}return{success:!1,error:e}}return{success:!0,data:(await s.json()).data}}catch(e){return log(`[portal-api-client] saveMyPrompt FATAL: ${e.message}`),{success:!1,error:t("mcp.portalCommunicationError",{error:e.message})}}}async function deleteMyPrompt(e,r){try{if(log(`[portal-api-client] deleteMyPrompt called: id=${e}`),!r)return{success:!1,error:t("mcp.noAuthToken")};const o=`${PORTAL_URL}/cli/my-agents/${encodeURIComponent(e)}`,s=await fetch(o,{method:"DELETE",headers:{"X-CLI-Token":r,"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:o.startsWith("https")?httpsAgent:void 0});if(!s.ok){const t=await s.text();log(`[portal-api-client] deleteMyPrompt error: ${s.status}`);let e=`HTTP ${s.status}`;try{const r=JSON.parse(t);r.message&&(e=r.message)}catch(t){}return{success:!1,error:e}}return{success:!0,data:(await s.json()).data}}catch(e){return log(`[portal-api-client] deleteMyPrompt FATAL: ${e.message}`),{success:!1,error:t("mcp.portalCommunicationError",{error:e.message})}}}async function downloadMcpPackage(e,r){try{if(log(`[portal-api-client] downloadMcpPackage called: mcpId=${e}`),!r)return{success:!1,error:t("mcp.noAuthToken")};const o=`${PORTAL_URL}/mcp/${encodeURIComponent(e)}/download`;log(`[portal-api-client] Downloading MCP package: ${o}`);const s=await fetch(o,{method:"GET",headers:{"X-CLI-Token":r,"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:o.startsWith("https")?httpsAgent:void 0});if(!s.ok){const t=await s.text();log(`[portal-api-client] downloadMcpPackage error: ${s.status} ${t}`);let e=`Download failed: HTTP ${s.status}`;try{const r=JSON.parse(t);r.message&&(e=r.message)}catch(t){}return{success:!1,error:e}}const a=await s.json();return log(`[portal-api-client] downloadMcpPackage: ${a.data?.files?.length||0} files`),{success:!0,data:a.data}}catch(e){return log(`[portal-api-client] downloadMcpPackage FATAL: ${e.message}`),{success:!1,error:t("mcp.portalCommunicationError",{error:e.message})}}}async function getGatewayConfig(t){try{if(!t)return{success:!1,error:"No token"};const e=`${PORTAL_URL}/mcp/user/me/gateway-config`;log(`[portal-api-client] getGatewayConfig: ${e}`);const r=await fetch(e,{method:"GET",headers:{"X-CLI-Token":t,"Content-Type":"application/json"},agent:e.startsWith("https")?httpsAgent:void 0});if(!r.ok)return{success:!1,error:`HTTP ${r.status}`};const o=await r.json();return log(`[portal-api-client] getGatewayConfig: ${o.data?.services?.length||0} services`),{success:!0,data:o.data}}catch(t){return log(`[portal-api-client] getGatewayConfig error: ${t.message}`),{success:!1,error:t.message}}}async function searchMcpServices(t,e){try{if(!e)return{success:!1,error:"No token"};const r=`${PORTAL_URL}/mcp/search?q=${encodeURIComponent(t)}`;log(`[portal-api-client] searchMcpServices: ${r}`);const o=await fetch(r,{method:"GET",headers:{"X-CLI-Token":e,"Content-Type":"application/json"},agent:r.startsWith("https")?httpsAgent:void 0});return o.ok?{success:!0,data:(await o.json()).data}:{success:!1,error:`HTTP ${o.status}`}}catch(t){return log(`[portal-api-client] searchMcpServices error: ${t.message}`),{success:!1,error:t.message}}}async function installMcpService(t,e,r,o){try{if(!r)return{success:!1,error:"No token"};const s=`${PORTAL_URL}/mcp/user/me/install`,a={mcpId:t,alwaysOn:e??!1};o&&Object.keys(o).length>0&&(a.envOverrides=o);const n=await fetch(s,{method:"POST",headers:{"X-CLI-Token":r,"Content-Type":"application/json"},agent:s.startsWith("https")?httpsAgent:void 0,body:JSON.stringify(a)});return n.ok?{success:!0,data:(await n.json()).data}:{success:!1,error:`HTTP ${n.status}`}}catch(t){return log(`[portal-api-client] installMcpService error: ${t.message}`),{success:!1,error:t.message}}}async function setServiceDeactivated(t,e,r){try{if(!r)return{success:!1,error:"No token"};const o=e?"deactivate":"activate",s=`${PORTAL_URL}/mcp/user/me/services/${encodeURIComponent(t)}/${o}`,a=await fetch(s,{method:"POST",headers:{"X-CLI-Token":r,"Content-Type":"application/json"},agent:s.startsWith("https")?httpsAgent:void 0});return a.ok?{success:!0,data:(await a.json()).data}:{success:!1,error:`HTTP ${a.status}`}}catch(t){return log(`[portal-api-client] setServiceDeactivated error: ${t.message}`),{success:!1,error:t.message}}}async function uninstallMcpService(t,e){try{if(!e)return{success:!1,error:"No token"};const r=`${PORTAL_URL}/mcp/user/me/services/${encodeURIComponent(t)}`,o=await fetch(r,{method:"DELETE",headers:{"X-CLI-Token":e,"Content-Type":"application/json"},agent:r.startsWith("https")?httpsAgent:void 0});return o.ok?{success:!0,data:(await o.json()).data}:{success:!1,error:`HTTP ${o.status}`}}catch(t){return log(`[portal-api-client] uninstallMcpService error: ${t.message}`),{success:!1,error:t.message}}}async function updateMcpEnv(t,e,r){try{if(!r)return{success:!1,error:"No token"};const o=`${PORTAL_URL}/mcp/user/me/services/${encodeURIComponent(t)}/env`,s=await fetch(o,{method:"PUT",headers:{"X-CLI-Token":r,"Content-Type":"application/json"},agent:o.startsWith("https")?httpsAgent:void 0,body:JSON.stringify({env:e})});if(!s.ok)return{success:!1,error:`HTTP ${s.status}`};const a=await s.json();return{success:!0,data:a.data,warning:a.warning||null}}catch(t){return log(`[portal-api-client] updateMcpEnv error: ${t.message}`),{success:!1,error:t.message}}}async function callMcpToolProxy(t,e,r,o){try{if(!o)return{success:!1,error:"No token"};const s=`${PORTAL_URL}/mcp/${encodeURIComponent(t)}/call`,a=await fetch(s,{method:"POST",headers:{"X-CLI-Token":o,...activeTenantHeaders(),"Content-Type":"application/json"},agent:s.startsWith("https")?httpsAgent:void 0,body:JSON.stringify({tool_name:e,arguments:r})});if(!a.ok){const t=await a.text();return{success:!1,error:`HTTP ${a.status}: ${t.slice(0,200)}`}}return await a.json()}catch(t){return log(`[portal-api-client] callMcpToolProxy error: ${t.message}`),{success:!1,error:t.message}}}fs.existsSync(LOG_DIR)||fs.mkdirSync(LOG_DIR,{recursive:!0}),module.exports={getPromptFromPortal:getPromptFromPortal,getSlotConfig:getSlotConfig,reportViolation:reportViolation,listAvailableMcps:listAvailableMcps,getMcpInfo:getMcpInfo,downloadMcpPackage:downloadMcpPackage,callMcpTool:callMcpTool,scanMcpCode:scanMcpCode,deployUserMcp:deployUserMcp,listUserCreatedMcps:listUserCreatedMcps,deleteUserMcp:deleteUserMcp,listMyPrompts:listMyPrompts,saveMyPrompt:saveMyPrompt,deleteMyPrompt:deleteMyPrompt,getGatewayConfig:getGatewayConfig,searchMcpServices:searchMcpServices,installMcpService:installMcpService,setServiceDeactivated:setServiceDeactivated,uninstallMcpService:uninstallMcpService,updateMcpEnv:updateMcpEnv,callMcpToolProxy:callMcpToolProxy};
|
|
1
|
+
const fetch=(...t)=>import("node-fetch").then(({default:e})=>e(...t)),https=require("https"),fs=require("fs"),path=require("path"),os=require("os"),{requireFromPackage:requireFromPackage}=require("../requireFromPackage.cjs"),{logger:logger}=requireFromPackage(require,"../../utils/logger"),{t:t}=requireFromPackage(require,"../../i18n"),PORTAL_URL_ENV=process.env.BLUELAMP_PORTAL_API_BASE_URL||process.env.PORTAL_URL||"",isDevEnvironment=PORTAL_URL_ENV.includes("localhost"),httpsAgent=new https.Agent({rejectUnauthorized:!isDevEnvironment}),PORTAL_URL=PORTAL_URL_ENV||(isDevEnvironment?"http://localhost:8430/api/bluelamp":"https://api.motohi.jp/api/bluelamp"),LOG_DIR=path.join(os.homedir(),".bluelamp-vscode","logs"),LOG_FILE=path.join(LOG_DIR,"mcp.log");function log(t){const e=`[${(new Date).toISOString()}] ${t}\n`;fs.appendFileSync(LOG_FILE,e),logger.debug(t)}function activeTenantHeaders(){const t=process.env.MUSUHI_TENANT_ID||"";return t?{"X-Tenant-ID":t}:{}}let _cliVersion;function getCliVersion(){if(void 0!==_cliVersion)return _cliVersion;let t=__dirname;for(let e=0;e<6;e++){try{const e=require(path.join(t,"package.json"));if(e&&e.version&&e.bin&&Object.keys(e.bin).some(t=>/^[a-z]+\d+$/.test(t)))return _cliVersion=e.version,_cliVersion}catch(t){}const e=path.dirname(t);if(e===t)break;t=e}return _cliVersion=null,_cliVersion}async function getPromptFromPortal(e,r,o="ja"){try{if(log(`[portal-api-client] getPromptFromPortal called, lang: ${o}, token: ${r?"present":"missing"}`),!r)return log("[portal-api-client] No authentication token provided"),{success:!1,error:t("mcp.noAuthToken")};const s=activeTenantHeaders()["X-Tenant-ID"],a=encodeURIComponent(e);let n=`${PORTAL_URL}/cli/prompts/knowledge-injection/${a}?lang=${o}`;s&&(n+=`&tenant_id=${encodeURIComponent(s)}`),log("[portal-api-client] Direct keyword search"),log("[portal-api-client] About to call fetch...");const c=await fetch(n,{method:"GET",headers:{"X-CLI-Token":r,...getCliVersion()?{"X-CLI-Version":getCliVersion()}:{},...activeTenantHeaders(),"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:n.startsWith("https")?httpsAgent:void 0});if(log("[portal-api-client] Fetch completed"),log(`[portal-api-client] Response status: ${c.status}`),log(`[portal-api-client] Response headers: ${JSON.stringify(Object.fromEntries(c.headers.entries()))}`),!c.ok){log(`[portal-api-client] Portal API error: ${c.status}`);const e=await c.text();log(`[portal-api-client] Error response: ${e}`);let r=t("mcp.portalApiError",{status:c.status}),o=null;try{const t=JSON.parse(e);t.message&&(r=t.message),t.code&&(o=t.code)}catch(t){}return{success:!1,error:r,status:c.status,code:o}}const i=await c.json();if(log("[portal-api-client] Direct keyword search completed successfully"),!i.success)return log("[portal-api-client] API returned success: false"),{success:!1,error:i.message||t("mcp.apiReturnedError")};const l=i.data;if(!l)return log("[portal-api-client] No prompt found"),{success:!1,error:t("mcp.promptNotFoundForKeyword",{keyword:e})};if(log(`[portal-api-client] Found prompt: ${l.title}`),l.content||l.text)return{success:!0,knowledge:l.content||l.text,title:l.title,tags:l.tags||[]};try{const t=`${PORTAL_URL}/cli/prompts/${l.id}`;log(`[portal-api-client] Fetching prompt details from: ${t}`);const e=await fetch(t,{method:"GET",headers:{"X-CLI-Token":r,"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:httpsAgent});if(e.ok){const t=await e.json();if(t.success&&t.data?.prompt?.content)return log("[portal-api-client] Successfully fetched prompt content"),{success:!0,knowledge:t.data.prompt.content,title:l.title||l.name,tags:l.tags}}}catch(t){log(`[portal-api-client] Error fetching prompt details: ${t.message}`)}return{success:!0,knowledge:l.description||`# ${l.title}\n\n${t("mcp.knowledgeLoadError",{error:"detail fetch failed"})}`,title:l.title||l.name,tags:l.tags}}catch(e){return log(`[portal-api-client] FATAL ERROR in getPromptFromPortal: ${e.message}`),log(`[portal-api-client] Error stack: ${e.stack}`),logger.error(`Failed to get prompt from Portal: ${e.message}`),{success:!1,error:t("mcp.portalCommunicationError",{error:e.message}),networkFailure:Boolean(e&&"FetchError"===e.name)}}}async function getSlotConfig(t,e){try{if(!e)return log("[portal-api-client] getSlotConfig: No token"),{ok:!1,reason:"no-token"};const r=activeTenantHeaders()["X-Tenant-ID"],o=`${PORTAL_URL}/cli/slot-config/${t}`;log(`[portal-api-client] Fetching slot config: ${o}${r?` (tenant=${r})`:""}`);const s=await fetch(o,{method:"GET",headers:{"X-CLI-Token":e,...getCliVersion()?{"X-CLI-Version":getCliVersion()}:{},...activeTenantHeaders(),"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:o.startsWith("https")?httpsAgent:void 0});if(!s.ok){log(`[portal-api-client] Slot config API error: ${s.status}`);let t=null;try{const e=await s.json();t=e?.error?.message||e?.message||null}catch{t=null}return 404===s.status?{ok:!1,reason:"not-configured",status:404,message:t}:403===s.status?{ok:!1,reason:"rank",status:403,message:t}:{ok:!1,reason:"http",status:s.status,message:t}}const a=await s.json();return a.success&&a.data?.keyword?(log(`[portal-api-client] Slot ${t}: custom keyword set`),{ok:!0,keyword:a.data.keyword}):(log(`[portal-api-client] Slot ${t}: no custom config`),{ok:!0,keyword:null})}catch(t){return log(`[portal-api-client] getSlotConfig error: ${t.message}`),{ok:!1,reason:"network",status:null,message:t.message}}}async function reportViolation(e,r,o,s){try{if(log(`[portal-api-client] reportViolation called: severity=${r}`),!o)return{success:!1,error:t("mcp.violationNoToken")};const a=`${PORTAL_URL}/cli/report-violation`,n={reason:e,severity:r};s&&(n.userMessage=s);const c=await fetch(a,{method:"POST",headers:{"X-CLI-Token":o,"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:a.startsWith("https")?httpsAgent:void 0,body:JSON.stringify(n)});if(!c.ok){const e=await c.text();return log(`[portal-api-client] reportViolation error: ${c.status} ${e}`),{success:!1,error:t("mcp.violationApiError",{status:c.status})}}const i=await c.json();return log(`[portal-api-client] reportViolation result: action=${i.action}, count=${i.violationCount}`),i}catch(e){return log(`[portal-api-client] reportViolation FATAL: ${e.message}`),{success:!1,error:t("mcp.violationCommunicationError",{error:e.message})}}}async function listAvailableMcps(e={},r,o="ja"){try{if(log(`[portal-api-client] listAvailableMcps called: ${JSON.stringify(e)}`),!r)return{success:!1,error:t("mcp.noAuthToken")};const s=new URLSearchParams;e.search&&s.set("search",e.search),e.limit&&s.set("limit",String(e.limit)),s.set("lang",o);const a=`${PORTAL_URL}/mcp/catalog?${s.toString()}`;log(`[portal-api-client] Fetching MCP catalog: ${a}`);const n=await fetch(a,{method:"GET",headers:{"X-CLI-Token":r,"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:a.startsWith("https")?httpsAgent:void 0});if(!n.ok){const e=await n.text();log(`[portal-api-client] listAvailableMcps error: ${n.status} ${e}`);let r=t("mcp.listMcpsFailed",{error:`HTTP ${n.status}`});try{const t=JSON.parse(e);t.message&&(r=t.message)}catch(t){}return{success:!1,error:r}}const c=await n.json();return log(`[portal-api-client] listAvailableMcps: ${c.data?.length||0} MCPs found`),{success:!0,data:c.data||[]}}catch(e){return log(`[portal-api-client] listAvailableMcps FATAL: ${e.message}`),{success:!1,error:t("mcp.portalCommunicationError",{error:e.message})}}}async function getMcpInfo(e,r,o="ja"){try{if(log(`[portal-api-client] getMcpInfo called: mcpId=${e}`),!r)return{success:!1,error:t("mcp.noAuthToken")};const s=`${PORTAL_URL}/mcp/${encodeURIComponent(e)}/details?lang=${o}`;log(`[portal-api-client] Fetching MCP info: ${s}`);const a=await fetch(s,{method:"GET",headers:{"X-CLI-Token":r,"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:s.startsWith("https")?httpsAgent:void 0});if(!a.ok){const e=await a.text();log(`[portal-api-client] getMcpInfo error: ${a.status} ${e}`);let r=t("mcp.getMcpInfoFailed",{error:`HTTP ${a.status}`});try{const t=JSON.parse(e);t.message&&(r=t.message)}catch(t){}return{success:!1,error:r}}const n=await a.json();return log(`[portal-api-client] getMcpInfo: found ${n.data?.name||e}`),{success:!0,data:n.data}}catch(e){return log(`[portal-api-client] getMcpInfo FATAL: ${e.message}`),{success:!1,error:t("mcp.portalCommunicationError",{error:e.message})}}}async function callMcpTool(e,r,o,s){try{if(log(`[portal-api-client] callMcpTool called: mcpId=${e}, tool=${r}`),!s)return{success:!1,error:t("mcp.noAuthToken")};const a=`${PORTAL_URL}/mcp/${encodeURIComponent(e)}/call`,n={tool_name:r,arguments:o};log(`[portal-api-client] Calling MCP tool: ${a}`);const c=await fetch(a,{method:"POST",headers:{"X-CLI-Token":s,...activeTenantHeaders(),"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:a.startsWith("https")?httpsAgent:void 0,body:JSON.stringify(n)});if(!c.ok){const e=await c.text();log(`[portal-api-client] callMcpTool error: ${c.status} ${e}`);let r=t("mcp.callToolFailed",{error:`HTTP ${c.status}`});try{const t=JSON.parse(e);t.message&&(r=t.message)}catch(t){}return{success:!1,error:r}}const i=await c.json();return log("[portal-api-client] callMcpTool: success"),{success:!0,data:i.data}}catch(e){return log(`[portal-api-client] callMcpTool FATAL: ${e.message}`),{success:!1,error:t("mcp.portalCommunicationError",{error:e.message})}}}async function scanMcpCode(e,r){try{if(log("[portal-api-client] scanMcpCode called"),!r)return{success:!1,error:t("mcp.noAuthToken")};const o=`${PORTAL_URL}/mcp/scan`,s=await fetch(o,{method:"POST",headers:{"X-CLI-Token":r,"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:o.startsWith("https")?httpsAgent:void 0,body:JSON.stringify({code:e})});if(!s.ok){const t=await s.text();return log(`[portal-api-client] scanMcpCode error: ${s.status} ${t}`),{success:!1,error:`HTTP ${s.status}`}}return{success:!0,data:(await s.json()).data}}catch(e){return log(`[portal-api-client] scanMcpCode FATAL: ${e.message}`),{success:!1,error:t("mcp.portalCommunicationError",{error:e.message})}}}async function deployUserMcp(e,r){try{if(log(`[portal-api-client] deployUserMcp called: name=${e.name}`),!r)return{success:!1,error:t("mcp.noAuthToken")};const o=`${PORTAL_URL}/mcp/deploy`,s=await fetch(o,{method:"POST",headers:{"X-CLI-Token":r,"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:o.startsWith("https")?httpsAgent:void 0,body:JSON.stringify(e)});if(!s.ok){const t=await s.text();log(`[portal-api-client] deployUserMcp error: ${s.status} ${t}`);let e=`HTTP ${s.status}`;try{const r=JSON.parse(t);if(r.error&&(e=r.error),r.details)return{success:!1,error:e,details:r.details}}catch(t){}return{success:!1,error:e}}return{success:!0,data:(await s.json()).data}}catch(e){return log(`[portal-api-client] deployUserMcp FATAL: ${e.message}`),{success:!1,error:t("mcp.portalCommunicationError",{error:e.message})}}}async function listUserCreatedMcps(e){try{if(log("[portal-api-client] listUserCreatedMcps called"),!e)return{success:!1,error:t("mcp.noAuthToken")};const r=`${PORTAL_URL}/mcp/user/me/created`,o=await fetch(r,{method:"GET",headers:{"X-CLI-Token":e,"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:r.startsWith("https")?httpsAgent:void 0});return o.ok?{success:!0,data:(await o.json()).data}:(await o.text(),log(`[portal-api-client] listUserCreatedMcps error: ${o.status}`),{success:!1,error:`HTTP ${o.status}`})}catch(e){return log(`[portal-api-client] listUserCreatedMcps FATAL: ${e.message}`),{success:!1,error:t("mcp.portalCommunicationError",{error:e.message})}}}async function deleteUserMcp(e,r){try{if(log(`[portal-api-client] deleteUserMcp called: mcpId=${e}`),!r)return{success:!1,error:t("mcp.noAuthToken")};const o=`${PORTAL_URL}/mcp/${encodeURIComponent(e)}`,s=await fetch(o,{method:"DELETE",headers:{"X-CLI-Token":r,"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:o.startsWith("https")?httpsAgent:void 0});if(!s.ok){const t=await s.text();log(`[portal-api-client] deleteUserMcp error: ${s.status}`);let e=`HTTP ${s.status}`;try{const r=JSON.parse(t);r.error&&(e=r.error)}catch(t){}return{success:!1,error:e}}return{success:!0,data:(await s.json()).data}}catch(e){return log(`[portal-api-client] deleteUserMcp FATAL: ${e.message}`),{success:!1,error:t("mcp.portalCommunicationError",{error:e.message})}}}async function listMyPrompts(e){try{if(log("[portal-api-client] listMyPrompts called"),!e)return{success:!1,error:t("mcp.noAuthToken")};const r=`${PORTAL_URL}/cli/my-agents`,o=await fetch(r,{method:"GET",headers:{"X-CLI-Token":e,"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:r.startsWith("https")?httpsAgent:void 0});return o.ok?{success:!0,data:(await o.json()).data||[]}:(await o.text(),log(`[portal-api-client] listMyPrompts error: ${o.status}`),{success:!1,error:`HTTP ${o.status}`})}catch(e){return log(`[portal-api-client] listMyPrompts FATAL: ${e.message}`),{success:!1,error:t("mcp.portalCommunicationError",{error:e.message})}}}async function saveMyPrompt(e,r){try{if(log(`[portal-api-client] saveMyPrompt called: title=${e.title}`),!r)return{success:!1,error:t("mcp.noAuthToken")};const o=`${PORTAL_URL}/cli/my-agents`,s=await fetch(o,{method:"POST",headers:{"X-CLI-Token":r,"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:o.startsWith("https")?httpsAgent:void 0,body:JSON.stringify(e)});if(!s.ok){const t=await s.text();log(`[portal-api-client] saveMyPrompt error: ${s.status} ${t}`);let e=`HTTP ${s.status}`;try{const r=JSON.parse(t);r.message&&(e=r.message)}catch(t){}return{success:!1,error:e}}return{success:!0,data:(await s.json()).data}}catch(e){return log(`[portal-api-client] saveMyPrompt FATAL: ${e.message}`),{success:!1,error:t("mcp.portalCommunicationError",{error:e.message})}}}async function deleteMyPrompt(e,r){try{if(log(`[portal-api-client] deleteMyPrompt called: id=${e}`),!r)return{success:!1,error:t("mcp.noAuthToken")};const o=`${PORTAL_URL}/cli/my-agents/${encodeURIComponent(e)}`,s=await fetch(o,{method:"DELETE",headers:{"X-CLI-Token":r,"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:o.startsWith("https")?httpsAgent:void 0});if(!s.ok){const t=await s.text();log(`[portal-api-client] deleteMyPrompt error: ${s.status}`);let e=`HTTP ${s.status}`;try{const r=JSON.parse(t);r.message&&(e=r.message)}catch(t){}return{success:!1,error:e}}return{success:!0,data:(await s.json()).data}}catch(e){return log(`[portal-api-client] deleteMyPrompt FATAL: ${e.message}`),{success:!1,error:t("mcp.portalCommunicationError",{error:e.message})}}}async function downloadMcpPackage(e,r){try{if(log(`[portal-api-client] downloadMcpPackage called: mcpId=${e}`),!r)return{success:!1,error:t("mcp.noAuthToken")};const o=`${PORTAL_URL}/mcp/${encodeURIComponent(e)}/download`;log(`[portal-api-client] Downloading MCP package: ${o}`);const s=await fetch(o,{method:"GET",headers:{"X-CLI-Token":r,"Content-Type":"application/json","User-Agent":"BlueLamp-VSCode-MCP/1.0"},agent:o.startsWith("https")?httpsAgent:void 0});if(!s.ok){const t=await s.text();log(`[portal-api-client] downloadMcpPackage error: ${s.status} ${t}`);let e=`Download failed: HTTP ${s.status}`;try{const r=JSON.parse(t);r.message&&(e=r.message)}catch(t){}return{success:!1,error:e}}const a=await s.json();return log(`[portal-api-client] downloadMcpPackage: ${a.data?.files?.length||0} files`),{success:!0,data:a.data}}catch(e){return log(`[portal-api-client] downloadMcpPackage FATAL: ${e.message}`),{success:!1,error:t("mcp.portalCommunicationError",{error:e.message})}}}async function getGatewayConfig(t){try{if(!t)return{success:!1,error:"No token"};const e=`${PORTAL_URL}/mcp/user/me/gateway-config`;log(`[portal-api-client] getGatewayConfig: ${e}`);const r=await fetch(e,{method:"GET",headers:{"X-CLI-Token":t,"Content-Type":"application/json"},agent:e.startsWith("https")?httpsAgent:void 0});if(!r.ok)return{success:!1,error:`HTTP ${r.status}`};const o=await r.json();return log(`[portal-api-client] getGatewayConfig: ${o.data?.services?.length||0} services`),{success:!0,data:o.data}}catch(t){return log(`[portal-api-client] getGatewayConfig error: ${t.message}`),{success:!1,error:t.message}}}async function searchMcpServices(t,e){try{if(!e)return{success:!1,error:"No token"};const r=`${PORTAL_URL}/mcp/search?q=${encodeURIComponent(t)}`;log(`[portal-api-client] searchMcpServices: ${r}`);const o=await fetch(r,{method:"GET",headers:{"X-CLI-Token":e,"Content-Type":"application/json"},agent:r.startsWith("https")?httpsAgent:void 0});return o.ok?{success:!0,data:(await o.json()).data}:{success:!1,error:`HTTP ${o.status}`}}catch(t){return log(`[portal-api-client] searchMcpServices error: ${t.message}`),{success:!1,error:t.message}}}async function installMcpService(t,e,r,o){try{if(!r)return{success:!1,error:"No token"};const s=`${PORTAL_URL}/mcp/user/me/install`,a={mcpId:t,alwaysOn:e??!1};o&&Object.keys(o).length>0&&(a.envOverrides=o);const n=await fetch(s,{method:"POST",headers:{"X-CLI-Token":r,"Content-Type":"application/json"},agent:s.startsWith("https")?httpsAgent:void 0,body:JSON.stringify(a)});return n.ok?{success:!0,data:(await n.json()).data}:{success:!1,error:`HTTP ${n.status}`}}catch(t){return log(`[portal-api-client] installMcpService error: ${t.message}`),{success:!1,error:t.message}}}async function setServiceDeactivated(t,e,r){try{if(!r)return{success:!1,error:"No token"};const o=e?"deactivate":"activate",s=`${PORTAL_URL}/mcp/user/me/services/${encodeURIComponent(t)}/${o}`,a=await fetch(s,{method:"POST",headers:{"X-CLI-Token":r,"Content-Type":"application/json"},agent:s.startsWith("https")?httpsAgent:void 0});return a.ok?{success:!0,data:(await a.json()).data}:{success:!1,error:`HTTP ${a.status}`}}catch(t){return log(`[portal-api-client] setServiceDeactivated error: ${t.message}`),{success:!1,error:t.message}}}async function uninstallMcpService(t,e){try{if(!e)return{success:!1,error:"No token"};const r=`${PORTAL_URL}/mcp/user/me/services/${encodeURIComponent(t)}`,o=await fetch(r,{method:"DELETE",headers:{"X-CLI-Token":e,"Content-Type":"application/json"},agent:r.startsWith("https")?httpsAgent:void 0});return o.ok?{success:!0,data:(await o.json()).data}:{success:!1,error:`HTTP ${o.status}`}}catch(t){return log(`[portal-api-client] uninstallMcpService error: ${t.message}`),{success:!1,error:t.message}}}async function updateMcpEnv(t,e,r){try{if(!r)return{success:!1,error:"No token"};const o=`${PORTAL_URL}/mcp/user/me/services/${encodeURIComponent(t)}/env`,s=await fetch(o,{method:"PUT",headers:{"X-CLI-Token":r,"Content-Type":"application/json"},agent:o.startsWith("https")?httpsAgent:void 0,body:JSON.stringify({env:e})});if(!s.ok)return{success:!1,error:`HTTP ${s.status}`};const a=await s.json();return{success:!0,data:a.data,warning:a.warning||null}}catch(t){return log(`[portal-api-client] updateMcpEnv error: ${t.message}`),{success:!1,error:t.message}}}async function callMcpToolProxy(t,e,r,o){try{if(!o)return{success:!1,error:"No token"};const s=`${PORTAL_URL}/mcp/${encodeURIComponent(t)}/call`,a=await fetch(s,{method:"POST",headers:{"X-CLI-Token":o,...activeTenantHeaders(),"Content-Type":"application/json"},agent:s.startsWith("https")?httpsAgent:void 0,body:JSON.stringify({tool_name:e,arguments:r})});if(!a.ok){const t=await a.text();return{success:!1,error:`HTTP ${a.status}: ${t.slice(0,200)}`}}return await a.json()}catch(t){return log(`[portal-api-client] callMcpToolProxy error: ${t.message}`),{success:!1,error:t.message}}}fs.existsSync(LOG_DIR)||fs.mkdirSync(LOG_DIR,{recursive:!0}),module.exports={getPromptFromPortal:getPromptFromPortal,getSlotConfig:getSlotConfig,reportViolation:reportViolation,listAvailableMcps:listAvailableMcps,getMcpInfo:getMcpInfo,downloadMcpPackage:downloadMcpPackage,callMcpTool:callMcpTool,scanMcpCode:scanMcpCode,deployUserMcp:deployUserMcp,listUserCreatedMcps:listUserCreatedMcps,deleteUserMcp:deleteUserMcp,listMyPrompts:listMyPrompts,saveMyPrompt:saveMyPrompt,deleteMyPrompt:deleteMyPrompt,getGatewayConfig:getGatewayConfig,searchMcpServices:searchMcpServices,installMcpService:installMcpService,setServiceDeactivated:setServiceDeactivated,uninstallMcpService:uninstallMcpService,updateMcpEnv:updateMcpEnv,callMcpToolProxy:callMcpToolProxy};
|
|
@@ -1,16 +1,29 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* 子の Claude Code
|
|
2
|
+
* 子の Claude Code に会話の記録を書かせるかを、起動の番号で決める(純関数)。
|
|
3
3
|
*
|
|
4
4
|
* `CLAUDE_CODE_SKIP_PROMPT_HISTORY=1` を付けると、~/.claude/projects の記録(本文・道具の返り)と
|
|
5
5
|
* ~/.claude/history.jsonl が書かれない(n=2468 の実測: 画面のある形でも記録 0 件・配下の席も 0 件)。
|
|
6
6
|
* 見張りの道具は記録の代わりに足跡(footprint-hook.cjs)を読む。
|
|
7
7
|
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
8
|
+
* - 箱 n=2475(主君裁定 10/04 帳簿 4068 の ④): 配っている席(1〜100=テナント・200〜300=公式)は必ず付ける。
|
|
9
|
+
* - 箱 n=2757(主君の答え 10/09): 101〜199(マイエージェントの帯・共有でもらった写しも含む)は付けない。
|
|
10
|
+
* 外側(scheduler・monster-orchestrator・利用者の env)が付けて起こしても、子の env から外す。
|
|
11
|
+
*
|
|
12
|
+
* ⛔ fail-closed: 番号が読めない・帯の外は「付ける」側に倒す(取り違えると配っている本文が記録に残る)。
|
|
13
|
+
* ⛔ 付ける側の子は、付いていなければ起こさない。起動子は spawn の直前に `transcriptFreeError` で子の env を検め、
|
|
14
|
+
* null でなければ止まる。
|
|
10
15
|
*/
|
|
11
16
|
export declare const SKIP_HISTORY_ENV = "CLAUDE_CODE_SKIP_PROMPT_HISTORY";
|
|
12
|
-
/**
|
|
13
|
-
export declare
|
|
14
|
-
|
|
15
|
-
|
|
17
|
+
/** マイエージェントの帯(Phase 175 の 3 帯のうち personal)。 */
|
|
18
|
+
export declare const KEEP_TRANSCRIPT_SLOT_MIN = 101;
|
|
19
|
+
export declare const KEEP_TRANSCRIPT_SLOT_MAX = 199;
|
|
20
|
+
/** この起動の番号で、子に会話の記録を残させるか(101〜199 の整数のときだけ true)。 */
|
|
21
|
+
export declare function keepsTranscript(slotNumber: unknown): boolean;
|
|
22
|
+
/**
|
|
23
|
+
* 組み立てた子の env に、記録の設定を最後に重ねた写しを返す(元の env は変えない)。
|
|
24
|
+
* 101〜199 なら鍵を外す/それ以外なら `1` で上書きする(利用者の `0` にも後勝ち)。
|
|
25
|
+
*/
|
|
26
|
+
export declare function transcriptEnvForSlot<T extends Record<string, string | undefined>>(slotNumber: unknown, env: Readonly<T>): Record<string, string | undefined>;
|
|
27
|
+
/** 子の env がこの番号の形か。そうでなければ止める理由(そうなら null)。101〜199 以外は `1` が要る。 */
|
|
28
|
+
export declare function transcriptFreeError(env: Readonly<Record<string, string | undefined>>, slotNumber: unknown): string | null;
|
|
16
29
|
//# sourceMappingURL=transcriptFree.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transcriptFree.d.ts","sourceRoot":"","sources":["../../src/lib/transcriptFree.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"transcriptFree.d.ts","sourceRoot":"","sources":["../../src/lib/transcriptFree.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,eAAO,MAAM,gBAAgB,oCAAoC,CAAC;AAElE,+CAA+C;AAC/C,eAAO,MAAM,wBAAwB,MAAM,CAAC;AAC5C,eAAO,MAAM,wBAAwB,MAAM,CAAC;AAE5C,qDAAqD;AACrD,wBAAgB,eAAe,CAAC,UAAU,EAAE,OAAO,GAAG,OAAO,CAO5D;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,EAC/E,UAAU,EAAE,OAAO,EACnB,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,GACf,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAOpC;AAED,mEAAmE;AACnE,wBAAgB,mBAAmB,CACjC,GAAG,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,EACjD,UAAU,EAAE,OAAO,GAClB,MAAM,GAAG,IAAI,CAKf"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";function
|
|
1
|
+
"use strict";function keepsTranscript(r){return"number"==typeof r&&Number.isInteger(r)&&r>=exports.KEEP_TRANSCRIPT_SLOT_MIN&&r<=exports.KEEP_TRANSCRIPT_SLOT_MAX}function transcriptEnvForSlot(r,t){if(keepsTranscript(r)){const r={...t};return delete r[exports.SKIP_HISTORY_ENV],r}return{...t,[exports.SKIP_HISTORY_ENV]:"1"}}function transcriptFreeError(r,t){if(keepsTranscript(t))return null;const e=r[exports.SKIP_HISTORY_ENV];return"1"===e?null:`${exports.SKIP_HISTORY_ENV}=1 が子の環境に入っていません(現在: ${void 0===e?"無し":JSON.stringify(e)})`}Object.defineProperty(exports,"__esModule",{value:!0}),exports.KEEP_TRANSCRIPT_SLOT_MAX=exports.KEEP_TRANSCRIPT_SLOT_MIN=exports.SKIP_HISTORY_ENV=void 0,exports.keepsTranscript=keepsTranscript,exports.transcriptEnvForSlot=transcriptEnvForSlot,exports.transcriptFreeError=transcriptFreeError,exports.SKIP_HISTORY_ENV="CLAUDE_CODE_SKIP_PROMPT_HISTORY",exports.KEEP_TRANSCRIPT_SLOT_MIN=101,exports.KEEP_TRANSCRIPT_SLOT_MAX=199;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transcriptFree.js","sourceRoot":"","sources":["../../src/lib/transcriptFree.ts"],"names":[],"mappings":";AAAA
|
|
1
|
+
{"version":3,"file":"transcriptFree.js","sourceRoot":"","sources":["../../src/lib/transcriptFree.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AASH,0CAOC;AAMD,oDAUC;AAGD,kDAQC;AAzCY,QAAA,gBAAgB,GAAG,iCAAiC,CAAC;AAElE,+CAA+C;AAClC,QAAA,wBAAwB,GAAG,GAAG,CAAC;AAC/B,QAAA,wBAAwB,GAAG,GAAG,CAAC;AAE5C,qDAAqD;AACrD,SAAgB,eAAe,CAAC,UAAmB;IACjD,OAAO,CACL,OAAO,UAAU,KAAK,QAAQ;QAC9B,MAAM,CAAC,SAAS,CAAC,UAAU,CAAC;QAC5B,UAAU,IAAI,gCAAwB;QACtC,UAAU,IAAI,gCAAwB,CACvC,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,SAAgB,oBAAoB,CAClC,UAAmB,EACnB,GAAgB;IAEhB,IAAI,eAAe,CAAC,UAAU,CAAC,EAAE,CAAC;QAChC,MAAM,IAAI,GAAuC,EAAE,GAAG,GAAG,EAAE,CAAC;QAC5D,OAAO,IAAI,CAAC,wBAAgB,CAAC,CAAC;QAC9B,OAAO,IAAI,CAAC;IACd,CAAC;IACD,OAAO,EAAE,GAAG,GAAG,EAAE,CAAC,wBAAgB,CAAC,EAAE,GAAG,EAAE,CAAC;AAC7C,CAAC;AAED,mEAAmE;AACnE,SAAgB,mBAAmB,CACjC,GAAiD,EACjD,UAAmB;IAEnB,IAAI,eAAe,CAAC,UAAU,CAAC;QAAE,OAAO,IAAI,CAAC;IAC7C,MAAM,CAAC,GAAG,GAAG,CAAC,wBAAgB,CAAC,CAAC;IAChC,IAAI,CAAC,KAAK,GAAG;QAAE,OAAO,IAAI,CAAC;IAC3B,OAAO,GAAG,wBAAgB,wBAAwB,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC;AAClG,CAAC"}
|
package/package.json
CHANGED