UNPKG

@gftdcojp/actor-sdk

Version:

Comprehensive TypeScript SDK for GFTD Actor Platform with Well-becoming Agent as default - Supporting mental wellness and personal growth through AI

1,565 lines (1,557 loc) 156 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/lib/index.ts var index_exports = {}; __export(index_exports, { API_VERSION: () => API_VERSION, ActorGitManager: () => ActorGitManager, ActorRepositoryManager: () => ActorRepositoryManager, ActorV3ChatClient: () => ActorV3ChatClient, ActorV3Client: () => ActorV3Client, ActorV3Runnable: () => ActorV3Runnable, ChatGitManager: () => ChatGitManager, ChatHistoryQueryBuilder: () => ChatHistoryQueryBuilder, DEFAULT_ACTOR_TEMPLATES: () => DEFAULT_ACTOR_TEMPLATES, Features: () => Features, GFTDAuthClient: () => GFTDAuthClient, GFTDAuthError: () => GFTDAuthError, GFTDAuthMiddleware: () => GFTDAuthMiddleware, GitEmbeddingSDK: () => GitEmbeddingSDK, GitFileSystem: () => GitFileSystem, GitLabClient: () => GitLabClient, GitVectorStore: () => GitVectorStore, LangChainCompatibility: () => LangChainCompatibility, PROCESS_ALGEBRA_ENABLED: () => PROCESS_ALGEBRA_ENABLED, ProcessAlgebra: () => ProcessAlgebra, SDKConfigManager: () => SDKConfigManager, SDK_VERSION: () => SDK_VERSION, VectorStore: () => VectorStore, actorV3Api: () => actorV3Api, actorV3ChatClient: () => actorV3ChatClient, actorV3ToLangChain: () => actorV3ToLangChain, bulkRestoreSessions: () => bulkRestoreSessions, cn: () => cn, createAuthMiddleware: () => createAuthMiddleware, createConfigFromEnv: () => createConfigFromEnv, createConfigWithDefaultGitLab: () => createConfigWithDefaultGitLab, createDefaultChatGitConfig: () => createDefaultChatGitConfig, createDefaultConfig: () => createDefaultConfig, createDefaultSDKConfig: () => createDefaultSDKConfig, createDevelopmentConfig: () => createDevelopmentConfig, createLocalDevelopmentConfig: () => createLocalDevelopmentConfig, createMessage: () => createMessage, createProductionConfig: () => createProductionConfig, createSampleBehavior: () => createSampleBehavior, exportHistoryAsMarkdown: () => exportHistoryAsMarkdown, findActorSessions: () => findActorSessions, findSessionsByDateRange: () => findSessionsByDateRange, findSessionsByKeyword: () => findSessionsByKeyword, generateRepositoryName: () => generateRepositoryName, generateShortUUID: () => generateShortUUID, generateTimestampUUID: () => generateTimestampUUID, generateUUID: () => generateUUID, getSessionStatistics: () => getSessionStatistics, isLocalDevelopment: () => isLocalDevelopment, isToolEnabled: () => isToolEnabled, isValidShortUUID: () => isValidShortUUID, isValidUUID: () => isValidUUID, langChainToActorV3: () => langChainToActorV3, mergeConfig: () => mergeConfig, restoreSessionHistory: () => restoreSessionHistory, saveSessionHistory: () => saveSessionHistory, searchChatHistory: () => searchChatHistory, useActorV3Creation: () => useActorV3Creation, useActorV3Health: () => useActorV3Health, useActorV3List: () => useActorV3List, useActorV3Messaging: () => useActorV3Messaging, useActorV3Runnable: () => useActorV3Runnable, useActorV3System: () => useActorV3System, useAuth: () => useAuth, useGftdChat: () => useGftdChat, validateConfig: () => validateConfig }); module.exports = __toCommonJS(index_exports); // src/lib/types/actor-v3.ts function createMessage(label, payload, sender) { return { id: crypto.randomUUID(), label, payload, timestamp: (/* @__PURE__ */ new Date()).toISOString(), sender }; } function langChainToActorV3(lcMsg) { return { id: crypto.randomUUID(), label: lcMsg.name || "langchain_message", payload: { content: lcMsg.content }, timestamp: (/* @__PURE__ */ new Date()).toISOString(), sender: lcMsg.role === "user" ? "user" : void 0 }; } function actorV3ToLangChain(actorMsg) { return { role: actorMsg.sender ? "user" : "assistant", content: typeof actorMsg.payload === "string" ? actorMsg.payload : JSON.stringify(actorMsg.payload), name: actorMsg.label }; } // src/lib/types/config.ts function createDefaultConfig() { return { api: { baseUrl: "https://actor.gftd.ai/api/v3", timeout: 3e4, retryCount: 3 }, tools: { actorManagement: true, sessionManagement: true, streaming: true, embedding: false, gitIntegration: false, chatGitManagement: false, monitoring: true, uiComponents: true }, auth: { required: false, provider: "gftd" }, session: { max_iterations: 100, auto_save: true }, streaming: { enabled: true, chunkSize: 1024, timeout: 60, reconnect: { enabled: true, maxAttempts: 3, interval: 5e3 } }, monitoring: { metricsEnabled: true, logLevel: "info", performanceTracking: false, errorReporting: false }, ui: { theme: "auto", locale: "ja", defaultPageSize: 20, animations: true }, debug: { enabled: false, verboseLogging: false, logApiCalls: false, logGitOperations: false, measurePerformance: false } }; } function createDevelopmentConfig() { const baseConfig = createDefaultConfig(); return { ...baseConfig, api: { ...baseConfig.api, baseUrl: "https://actor.gftd.ai/api/v3" }, tools: { ...baseConfig.tools, gitIntegration: true, chatGitManagement: true, embedding: true, monitoring: true }, auth: { required: false, provider: "gftd" }, debug: { enabled: true, logApiCalls: true, logGitOperations: true } }; } function createProductionConfig() { const baseConfig = createDefaultConfig(); return { ...baseConfig, api: { ...baseConfig.api, baseUrl: "https://actor.gftd.ai/api/v3" }, auth: { required: true, provider: "gftd" }, debug: { enabled: false, logApiCalls: false, logGitOperations: false } }; } function mergeConfig(...configs) { const baseConfig = { tools: { actorManagement: true, sessionManagement: true, streaming: true, embedding: false, gitIntegration: false, chatGitManagement: false, monitoring: true, uiComponents: true }, api: { baseUrl: process.env.ACTOR_API_BASE_URL || "https://api.gftd.ai", timeout: 30, retryCount: 3 } }; return configs.reduce((acc, config) => { if (!config) return acc; return { ...acc, ...config, tools: config.tools ? { ...acc.tools, ...config.tools } : acc.tools, api: config.api ? { ...acc.api, ...config.api } : acc.api, auth: config.auth ? { ...acc.auth, ...config.auth } : acc.auth, session: config.session ? { ...acc.session, ...config.session } : acc.session, embedding: config.embedding ? { ...acc.embedding, ...config.embedding } : acc.embedding, git: config.git ? { ...acc.git, ...config.git } : acc.git, chatGit: config.chatGit ? { ...acc.chatGit, ...config.chatGit } : acc.chatGit, streaming: config.streaming ? { ...acc.streaming, ...config.streaming } : acc.streaming, monitoring: config.monitoring ? { ...acc.monitoring, ...config.monitoring } : acc.monitoring, ui: config.ui ? { ...acc.ui, ...config.ui } : acc.ui, debug: config.debug ? { ...acc.debug, ...config.debug } : acc.debug, custom: config.custom ? { ...acc.custom, ...config.custom } : acc.custom }; }, baseConfig); } function validateConfig(config) { const errors = []; if (!config.api?.baseUrl) { errors.push("api.baseUrl is required"); } return { valid: errors.length === 0, errors }; } function isToolEnabled(config, tool) { return config.tools[tool] === true; } function createConfigFromEnv() { const config = {}; if (process.env.ACTOR_API_BASE_URL) { config.api = { baseUrl: process.env.ACTOR_API_BASE_URL, apiKey: process.env.ACTOR_API_KEY, timeout: process.env.ACTOR_API_TIMEOUT ? parseInt(process.env.ACTOR_API_TIMEOUT) : void 0 }; } if (process.env.GFTD_AUTH_URL || process.env.GFTD_AUTH_API_KEY) { config.auth = { required: process.env.GFTD_AUTH_REQUIRED !== "false", authUrl: process.env.GFTD_AUTH_URL || "https://auth.gftd.ai", apiKey: process.env.GFTD_AUTH_API_KEY, provider: "gftd", tokenExpiry: process.env.GFTD_AUTH_TOKEN_EXPIRY ? parseInt(process.env.GFTD_AUTH_TOKEN_EXPIRY) : 3600, scopes: process.env.GFTD_AUTH_SCOPES ? process.env.GFTD_AUTH_SCOPES.split(",") : ["read", "write"], autoRefresh: process.env.GFTD_AUTH_AUTO_REFRESH !== "false", redirectUrl: process.env.GFTD_AUTH_REDIRECT_URL }; } if (process.env.NODE_ENV === "development") { config.debug = { enabled: true, verboseLogging: true, logApiCalls: true, logGitOperations: true }; } return config; } function createLocalDevelopmentConfig(organizationId) { const baseConfig = createDevelopmentConfig(); return { ...baseConfig, api: { ...baseConfig.api, baseUrl: "https://actor.gftd.ai/api/v3" }, tools: { ...baseConfig.tools, gitIntegration: true, chatGitManagement: true, embedding: true, monitoring: true }, auth: { required: false, provider: "gftd" }, debug: { enabled: true, logApiCalls: true, logGitOperations: true } }; } function isLocalDevelopment() { return process.env.NODE_ENV === "development"; } function createConfigWithDefaultGitLab(overrides) { const defaultGitLabConfig = { git: { autoCommit: process.env.GIT_AUTO_COMMIT === "true", autoPush: process.env.GIT_AUTO_PUSH === "true", defaultBranch: process.env.GIT_DEFAULT_BRANCH || "main" }, tools: { gitIntegration: true, chatGitManagement: true, actorManagement: true, sessionManagement: true, streaming: true, embedding: false, monitoring: true, uiComponents: true } }; const baseConfig = createDefaultConfig(); return mergeConfig(baseConfig, defaultGitLabConfig, overrides || {}); } // src/lib/api/actor-v3-client.ts var ActorV3Client = class { constructor(config = {}) { /** * アクター管理API */ this.actors = { /** * 新しいアクターを作成 */ create: async (request) => { return this.request("/actor", { method: "POST", body: JSON.stringify(request) }); }, /** * アクター一覧を取得 */ list: async (organizationId) => { const params = organizationId ? `?organization_id=${organizationId}` : ""; return this.request(`/actor${params}`); }, /** * アクターにメッセージを送信 */ send: async (actorId, request) => { const messageWithMetadata = { ...request.message, id: crypto.randomUUID(), timestamp: (/* @__PURE__ */ new Date()).toISOString() }; return this.request(`/actor/${actorId}/send`, { method: "POST", body: JSON.stringify({ ...request, message: messageWithMetadata }) }); }, /** * アクターからメッセージを受信 */ receive: async (actorId, request = {}) => { const params = new URLSearchParams(); if (request.max_messages) params.append("max_messages", request.max_messages.toString()); if (request.timeout) params.append("timeout", request.timeout.toString()); if (request.filter?.labels) params.append("filter_labels", request.filter.labels.join(",")); if (request.filter?.sender) params.append("filter_sender", request.filter.sender); const queryString = params.toString(); const url = `/actor/${actorId}/receive${queryString ? `?${queryString}` : ""}`; return this.request(url); }, /** * アクターを削除 */ delete: async (actorId) => { return this.request(`/actor/${actorId}`, { method: "DELETE" }); } }; /** * システム管理API */ this.system = { /** * システム設定を取得(プロセス代数分析含む) */ getConfig: async () => { return this.request("/system/config"); }, /** * システム統計を取得 */ getStats: async () => { return this.request("/system/stats"); } }; this.baseUrl = config.baseUrl || "https://actor.gftd.ai/api/v3"; this.apiKey = config.apiKey; } async request(endpoint, options = {}) { const url = `${this.baseUrl}${endpoint}`; const headers = { "Content-Type": "application/json", ...options.headers }; if (this.apiKey) { headers.Authorization = `Bearer ${this.apiKey}`; } try { const response = await fetch(url, { ...options, headers }); const data = await response.json(); if (!response.ok) { return { success: false, error: { code: data.code || "HTTP_ERROR", message: data.message || `HTTP ${response.status}: ${response.statusText}`, details: data.details } }; } return { success: true, data }; } catch (error) { return { success: false, error: { code: "NETWORK_ERROR", message: error instanceof Error ? error.message : "Unknown network error" } }; } } }; var ActorV3Runnable = class { constructor(actorId, client) { this.actorId = actorId; this.client = client; } /** * LangChain.js invoke() 互換メソッド */ async invoke(input, config) { const message = typeof input === "string" ? createMessage("invoke", { content: input }) : langChainToActorV3({ role: "user", content: typeof input === "string" ? input : JSON.stringify(input) }); const sendResult = await this.client.actors.send(this.actorId, { target: this.actorId, message }); if (!sendResult.success) { throw new Error(`Failed to send message: ${sendResult.error?.message}`); } const receiveResult = await this.client.actors.receive(this.actorId, { max_messages: 1, timeout: config?.timeout || 3e4 }); if (!receiveResult.success) { throw new Error(`Failed to receive message: ${receiveResult.error?.message}`); } const { messages, behavior_results } = receiveResult.data; if (behavior_results.length > 0 && behavior_results[0].actions.length > 0) { const outAction = behavior_results[0].actions[0]; if (outAction.type === "send" && outAction.message) { return actorV3ToLangChain(outAction.message); } } if (messages.length > 0) { return actorV3ToLangChain(messages[0]); } return { role: "assistant", content: "No response generated" }; } /** * LangChain.js stream() 互換メソッド */ async *stream(input, config) { const message = typeof input === "string" ? createMessage("stream", { content: input }) : langChainToActorV3({ role: "user", content: typeof input === "string" ? input : JSON.stringify(input) }); await this.client.actors.send(this.actorId, { target: this.actorId, message }); let receivedCount = 0; const maxMessages = config?.maxMessages || 10; while (receivedCount < maxMessages) { const { data } = await this.client.actors.receive(this.actorId, { max_messages: 1, timeout: 1e3 }); if (data?.messages && data.messages.length > 0) { for (const msg of data.messages) { yield actorV3ToLangChain(msg); receivedCount++; } } else { break; } } } /** * LangChain.js batch() 互換メソッド */ async batch(inputs, config) { const promises = inputs.map((input) => this.invoke(input, config)); return Promise.all(promises); } /** * LangChain.js pipe() 互換メソッド */ pipe(next) { return next; } /** * LangChain.js withFallbacks() 互換メソッド */ withFallbacks(fallbacks) { return this; } }; var actorV3Api = new ActorV3Client(); function createSampleBehavior(name, description) { return { id: crypto.randomUUID(), name, description, version: "1.0.0", handler: async (message, state) => { return { new_state: { ...state, last_message: message }, actions: [{ type: "send", target: message.sender, message: createMessage("response", { content: `Echo: ${JSON.stringify(message.payload)}` }) }] }; }, metadata: { created_at: (/* @__PURE__ */ new Date()).toISOString(), updated_at: (/* @__PURE__ */ new Date()).toISOString(), author: "system", tags: ["sample", "echo"], capabilities: ["message_processing"] }, process_algebra: { notation: "CCS", expression: `${name}(x) = x?.input(msg).x!output(echo(msg)).${name}(x)`, channels: ["input", "output"] } }; } // src/lib/api/chat-client.ts var ActorV3ChatClient = class { constructor(baseUrl = "https://actor.gftd.ai/api/v3", organizationId = "actors", apiKey) { this.currentActorId = null; this.baseUrl = baseUrl.replace(/\/$/, ""); this.organizationId = organizationId; this.headers = { "Content-Type": "application/json", "Accept": "application/json" }; if (apiKey) { this.headers["Authorization"] = `Bearer ${apiKey}`; } } /** * LangChain Actor を作成 * @param config LangChain Actor設定 * @returns LangChain Actor作成レスポンス */ async createLangChainActor(config) { try { const actorConfig = { name: config.name || "GFTD Chat Assistant", description: config.description || "AI\u4F1A\u8A71\u30A2\u30B7\u30B9\u30BF\u30F3\u30C8", model: config.model || "gpt-3.5-turbo", temperature: config.temperature || 0.7, max_tokens: config.max_tokens || 1e3, system_prompt: config.system_prompt || "\u3042\u306A\u305F\u306F\u89AA\u5207\u3067\u77E5\u8B58\u8C4A\u5BCC\u306AAI\u30A2\u30B7\u30B9\u30BF\u30F3\u30C8\u3067\u3059\u3002", organization_id: this.organizationId, max_history_length: config.max_history_length || 50, ...config }; const response = await fetch(`${this.baseUrl}/langchain/actor`, { method: "POST", headers: this.headers, body: JSON.stringify(actorConfig) }); if (!response.ok) { throw new Error(`LangChain Actor\u4F5C\u6210\u30A8\u30E9\u30FC: ${response.status} ${response.statusText}`); } const data = await response.json(); this.currentActorId = data.actor_id; return data; } catch (error) { console.error("LangChain Actor\u4F5C\u6210\u30A8\u30E9\u30FC:", error); throw error; } } /** * チャットメッセージを送信 * @param actorId Actor ID * @param request チャットリクエスト * @returns チャットレスポンス */ async sendChatMessage(actorId, request) { try { const response = await fetch(`${this.baseUrl}/langchain/actor/${actorId}/chat`, { method: "POST", headers: this.headers, body: JSON.stringify(request) }); if (!response.ok) { throw new Error(`\u30C1\u30E3\u30C3\u30C8\u30E1\u30C3\u30BB\u30FC\u30B8\u9001\u4FE1\u30A8\u30E9\u30FC: ${response.status} ${response.statusText}`); } const data = await response.json(); return data; } catch (error) { console.error("\u30C1\u30E3\u30C3\u30C8\u30E1\u30C3\u30BB\u30FC\u30B8\u9001\u4FE1\u30A8\u30E9\u30FC:", error); throw error; } } /** * 現在のActorでチャット(簡易版) * @param message メッセージ内容 * @param conversationId 会話ID(オプション) * @returns チャットレスポンス */ async chat(message, conversationId) { if (!this.currentActorId) { await this.createLangChainActor({}); } if (!this.currentActorId) { throw new Error("LangChain Actor\u306E\u4F5C\u6210\u306B\u5931\u6557\u3057\u307E\u3057\u305F"); } return this.sendChatMessage(this.currentActorId, { message, conversation_id: conversationId || "default-conversation" }); } /** * システムプロンプトを更新 * @param actorId Actor ID * @param systemPrompt 新しいシステムプロンプト */ async updateSystemPrompt(actorId, systemPrompt) { try { const response = await fetch(`${this.baseUrl}/langchain/actor/${actorId}/system-prompt`, { method: "PUT", headers: this.headers, body: JSON.stringify({ system_prompt: systemPrompt }) }); if (!response.ok) { throw new Error(`\u30B7\u30B9\u30C6\u30E0\u30D7\u30ED\u30F3\u30D7\u30C8\u66F4\u65B0\u30A8\u30E9\u30FC: ${response.status} ${response.statusText}`); } } catch (error) { console.error("\u30B7\u30B9\u30C6\u30E0\u30D7\u30ED\u30F3\u30D7\u30C8\u66F4\u65B0\u30A8\u30E9\u30FC:", error); throw error; } } /** * APIの健全性をチェック * @returns APIが利用可能かどうか */ async healthCheck() { try { const response = await fetch(`${this.baseUrl}/actor`, { method: "GET", headers: { "Accept": "application/json" }, // タイムアウトを追加 signal: AbortSignal.timeout(5e3) }); return response.ok; } catch (error) { return false; } } /** * 現在のActor IDを取得 * @returns 現在のActor ID */ getCurrentActorId() { return this.currentActorId; } /** * Actor IDを手動設定 * @param actorId 設定するActor ID */ setCurrentActorId(actorId) { this.currentActorId = actorId; } }; var actorV3ChatClient = new ActorV3ChatClient(); // src/hooks/use-actor-v3.ts var import_react = require("react"); function useActorV3List(organizationId) { const [actors, setActors] = (0, import_react.useState)([]); const [loading, setLoading] = (0, import_react.useState)(false); const [error, setError] = (0, import_react.useState)(null); const [totalCount, setTotalCount] = (0, import_react.useState)(0); const fetchActors = (0, import_react.useCallback)(async () => { setLoading(true); setError(null); try { console.log("\u{1F3AD} Fetching v3 actors with process algebra support:", organizationId); const response = await actorV3Api.actors.list(organizationId); if (response.success && response.data) { const actors2 = response.data.actors || []; const totalCount2 = response.data.total_count || 0; setActors(actors2); setTotalCount(totalCount2); console.log("\u2705 v3 actors loaded:", { count: actors2.length, total: totalCount2, actors: actors2.map((a) => ({ id: a?.actor_id || "unknown", name: a?.behavior_name || "unnamed", status: a?.status || "unknown" })) }); } else { setError(response.error?.message || "Failed to fetch v3 actors"); console.error("\u274C v3 actors fetch failed:", response.error); } } catch (err) { const errorMsg = err instanceof Error ? err.message : "Unknown error"; setError(errorMsg); console.warn("\u274C v3 actors fetch error:", err); } finally { setLoading(false); } }, [organizationId]); (0, import_react.useEffect)(() => { fetchActors(); }, [fetchActors]); const refetch = (0, import_react.useCallback)(() => { fetchActors(); }, [fetchActors]); return { actors, loading, error, totalCount, refetch }; } function useActorV3Creation() { const [loading, setLoading] = (0, import_react.useState)(false); const [error, setError] = (0, import_react.useState)(null); const createActor = (0, import_react.useCallback)(async (behavior, organizationId, initialState) => { setLoading(true); setError(null); try { console.log("\u{1F3AD} Creating v3 actor with process algebra behavior:", { name: behavior.name, version: behavior.version, processAlgebra: behavior.process_algebra, capabilities: behavior.metadata.capabilities }); const request = { behavior, organization_id: organizationId, initial_state: initialState }; const response = await actorV3Api.actors.create(request); if (response.success && response.data) { console.log("\u2705 v3 actor created:", { actor_id: response.data.actor_id, status: response.data.status, timestamp: response.data.timestamp }); return response.data; } else { setError(response.error?.message || "Failed to create v3 actor"); console.error("\u274C v3 actor creation failed:", response.error); return null; } } catch (err) { const errorMsg = err instanceof Error ? err.message : "Unknown error"; setError(errorMsg); console.error("\u274C v3 actor creation error:", err); return null; } finally { setLoading(false); } }, []); const createSampleActor = (0, import_react.useCallback)(async (name, description, organizationId) => { const behavior = createSampleBehavior(name, description); return createActor(behavior, organizationId); }, [createActor]); return { createActor, createSampleActor, loading, error }; } function useActorV3Messaging(actorId) { const [loading, setLoading] = (0, import_react.useState)(false); const [error, setError] = (0, import_react.useState)(null); const [messages, setMessages] = (0, import_react.useState)([]); const sendMessage = (0, import_react.useCallback)(async (label, payload, target) => { setLoading(true); setError(null); try { const message = createMessage(label, payload); const request = { target: target || actorId, message }; console.log("\u{1F4E8} Sending v3 message:", { actorId, label, payload, target: target || actorId }); const response = await actorV3Api.actors.send(actorId, request); if (response.success) { console.log("\u2705 v3 message sent:", response.data); return response.data; } else { setError(response.error?.message || "Failed to send message"); console.error("\u274C v3 message send failed:", response.error); return null; } } catch (err) { const errorMsg = err instanceof Error ? err.message : "Unknown error"; setError(errorMsg); console.error("\u274C v3 message send error:", err); return null; } finally { setLoading(false); } }, [actorId]); const receiveMessages = (0, import_react.useCallback)(async (request = {}) => { setLoading(true); setError(null); try { console.log("\u{1F4EC} Receiving v3 messages:", { actorId, request }); const response = await actorV3Api.actors.receive(actorId, request); if (response.success && response.data) { const newMessages = response.data.messages; setMessages((prev) => [...prev, ...newMessages]); console.log("\u2705 v3 messages received:", { count: newMessages.length, behavior_results: response.data.behavior_results.length }); return response.data; } else { setError(response.error?.message || "Failed to receive messages"); console.error("\u274C v3 message receive failed:", response.error); return null; } } catch (err) { const errorMsg = err instanceof Error ? err.message : "Unknown error"; setError(errorMsg); console.error("\u274C v3 message receive error:", err); return null; } finally { setLoading(false); } }, [actorId]); const clearMessages = (0, import_react.useCallback)(() => { setMessages([]); }, []); return { sendMessage, receiveMessages, clearMessages, messages, loading, error }; } function useActorV3Runnable(actorId) { const [runnable] = (0, import_react.useState)(() => new ActorV3Runnable(actorId, actorV3Api)); const [loading, setLoading] = (0, import_react.useState)(false); const [error, setError] = (0, import_react.useState)(null); const invoke = (0, import_react.useCallback)(async (input, config) => { setLoading(true); setError(null); try { console.log("\u{1F504} v3 LangChain invoke:", { actorId, input }); const result = await runnable.invoke(input, config); console.log("\u2705 v3 LangChain invoke result:", result); return result; } catch (err) { const errorMsg = err instanceof Error ? err.message : "Invoke failed"; setError(errorMsg); console.error("\u274C v3 LangChain invoke error:", err); throw err; } finally { setLoading(false); } }, [runnable, actorId]); const batch = (0, import_react.useCallback)(async (inputs, config) => { setLoading(true); setError(null); try { console.log("\u{1F504} v3 LangChain batch:", { actorId, inputs }); const results = await runnable.batch(inputs, config); console.log("\u2705 v3 LangChain batch results:", results); return results; } catch (err) { const errorMsg = err instanceof Error ? err.message : "Batch failed"; setError(errorMsg); console.error("\u274C v3 LangChain batch error:", err); throw err; } finally { setLoading(false); } }, [runnable, actorId]); return { runnable, invoke, batch, loading, error }; } function useActorV3System() { const [config, setConfig] = (0, import_react.useState)(null); const [stats, setStats] = (0, import_react.useState)(null); const [loading, setLoading] = (0, import_react.useState)(false); const [error, setError] = (0, import_react.useState)(null); const fetchConfig = (0, import_react.useCallback)(async () => { setLoading(true); setError(null); try { console.log("\u2699\uFE0F Fetching v3 system config with process algebra analysis"); const response = await actorV3Api.system.getConfig(); if (response.success && response.data) { setConfig(response.data); console.log("\u2705 v3 system config loaded:", { deadlock_free: response.data.process_algebra_analysis.deadlock_free, livelock_free: response.data.process_algebra_analysis.livelock_free, topology_edges: response.data.communication_topology.edges.length }); } else { const errorMsg = response.error?.message || "Failed to fetch system config"; setError(errorMsg); console.warn("\u26A0\uFE0F v3 system config fetch failed:", response.error); } } catch (err) { const errorMsg = err instanceof Error ? err.message : "Unknown error"; setError(errorMsg); console.warn("\u274C v3 system config fetch error:", err); } finally { setLoading(false); } }, []); const fetchStats = (0, import_react.useCallback)(async () => { setLoading(true); setError(null); try { console.log("\u{1F4CA} Fetching v3 system stats"); const response = await actorV3Api.system.getStats(); if (response.success && response.data) { setStats(response.data); console.log("\u2705 v3 system stats loaded:", { active_actors: response.data.stats.active_actors, total_messages: response.data.stats.total_messages, throughput: response.data.detailed_metrics.performance_metrics.throughput }); } else { const errorMsg = response.error?.message || "Failed to fetch system stats"; setError(errorMsg); console.warn("\u26A0\uFE0F v3 system stats fetch failed:", response.error); } } catch (err) { const errorMsg = err instanceof Error ? err.message : "Unknown error"; setError(errorMsg); console.warn("\u274C v3 system stats fetch error:", err); } finally { setLoading(false); } }, []); const refreshAll = (0, import_react.useCallback)(async () => { await Promise.all([fetchConfig(), fetchStats()]); }, [fetchConfig, fetchStats]); return { config, stats, loading, error, fetchConfig, fetchStats, refreshAll }; } function useActorV3Health() { const [status, setStatus] = (0, import_react.useState)("unknown"); const [lastChecked, setLastChecked] = (0, import_react.useState)(null); const [error, setError] = (0, import_react.useState)(null); const checkHealth = (0, import_react.useCallback)(async () => { setStatus("checking"); setError(null); try { console.log("\u{1F3E5} Checking v3 API health"); const response = await actorV3Api.actors.list(); if (response.success) { setStatus("healthy"); setLastChecked((/* @__PURE__ */ new Date()).toISOString()); console.log("\u2705 v3 API is healthy"); } else { setStatus("unhealthy"); setError(response.error?.message || "Health check failed"); console.warn("\u274C v3 API health check failed:", response.error); } } catch (err) { setStatus("unhealthy"); const errorMsg = err instanceof Error ? err.message : "Health check error"; setError(errorMsg); console.warn("\u274C v3 API health check error:", err); } }, []); (0, import_react.useEffect)(() => { checkHealth(); const interval = setInterval(checkHealth, 6e4); return () => clearInterval(interval); }, [checkHealth]); return { status, lastChecked, error, checkHealth }; } // src/hooks/use-gftd-chat.ts var import_react2 = require("react"); function useGftdChat(options = {}) { const { initialMessages = [], model = "gpt-3.5-turbo", temperature = 0.7, maxTokens = 1e3 } = options; const [messages, setMessages] = (0, import_react2.useState)(initialMessages); const [isLoading, setIsLoading] = (0, import_react2.useState)(false); const [error, setError] = (0, import_react2.useState)(null); const [isConnected, setIsConnected] = (0, import_react2.useState)(false); const lastUserMessageRef = (0, import_react2.useRef)(""); (0, import_react2.useEffect)(() => { const checkConnection = async () => { try { const connected = await actorV3ChatClient.healthCheck(); setIsConnected(connected); } catch (error2) { setIsConnected(false); } }; checkConnection(); const interval = setInterval(checkConnection, 3e5); return () => clearInterval(interval); }, []); const sendMessage = (0, import_react2.useCallback)(async (content) => { if (!content.trim()) return; if (isLoading) return; setError(null); setIsLoading(true); lastUserMessageRef.current = content; const userMessage = { id: `user-${Date.now()}`, role: "user", content: content.trim(), timestamp: /* @__PURE__ */ new Date() }; setMessages((prevMessages) => [...prevMessages, userMessage]); try { const response = await actorV3ChatClient.chat(content, "default-conversation"); if (!response || typeof response.content !== "string") { throw new Error("API\u304B\u3089\u7121\u52B9\u306A\u5FDC\u7B54\u304C\u8FD4\u3055\u308C\u307E\u3057\u305F"); } const assistantMessage = { id: `assistant-${Date.now()}`, role: "assistant", content: response.content, timestamp: /* @__PURE__ */ new Date() }; setMessages((prevMessages) => [...prevMessages, assistantMessage]); } catch (error2) { const errorMessage = error2 instanceof Error ? error2.message : "\u30E1\u30C3\u30BB\u30FC\u30B8\u306E\u9001\u4FE1\u306B\u5931\u6557\u3057\u307E\u3057\u305F"; setError(errorMessage); if (errorMessage.includes("fetch") || errorMessage.includes("network")) { console.warn("\u30C1\u30E3\u30C3\u30C8API\u63A5\u7D9A\u30A8\u30E9\u30FC:", errorMessage); } else { console.error("\u30C1\u30E3\u30C3\u30C8\u30E1\u30C3\u30BB\u30FC\u30B8\u9001\u4FE1\u30A8\u30E9\u30FC:", error2); const errorChatMessage = { id: `error-${Date.now()}`, role: "assistant", content: `\u274C \u30A8\u30E9\u30FC: ${errorMessage}`, timestamp: /* @__PURE__ */ new Date() }; setMessages((prevMessages) => [...prevMessages, errorChatMessage]); } } finally { setIsLoading(false); } }, [messages, isLoading, model, temperature, maxTokens]); const retryLastMessage = (0, import_react2.useCallback)(async () => { if (lastUserMessageRef.current && !isLoading) { await sendMessage(lastUserMessageRef.current); } }, [sendMessage, isLoading]); const clearMessages = (0, import_react2.useCallback)(() => { setMessages([]); setError(null); lastUserMessageRef.current = ""; }, []); return { messages, isLoading, error, isConnected, sendMessage, clearMessages, retryLastMessage, setMessages }; } // src/lib/config/sdk-config-manager.ts var DEFAULT_ACTOR_TEMPLATES = { "chat-assistant": { name: "Chat Assistant", description: "AI-powered chat assistant for conversations and Q&A", type: "chat-assistant", repositoryType: "local", gitConfig: { user: { name: "Actor SDK User", email: "user@actor-sdk.local" }, defaultBranch: "main", autoCommit: true, autoSync: false } }, "code-generator": { name: "Code Generator", description: "AI assistant specialized in code generation and programming help", type: "code-generator", repositoryType: "local", gitConfig: { user: { name: "Actor SDK User", email: "user@actor-sdk.local" }, defaultBranch: "main", autoCommit: true, autoSync: false } }, "document-processor": { name: "Document Processor", description: "AI assistant for document analysis and processing", type: "document-processor", repositoryType: "local", gitConfig: { user: { name: "Actor SDK User", email: "user@actor-sdk.local" }, defaultBranch: "main", autoCommit: true, autoSync: false } } }; function createDefaultSDKConfig() { return { version: "1.0.0", initialized: false, actors: {}, settings: { theme: "light", autoSave: true, showWelcome: true, defaultView: "actors" }, created: (/* @__PURE__ */ new Date()).toISOString(), lastModified: (/* @__PURE__ */ new Date()).toISOString() }; } var SDKConfigManager = class { /** * 実行環境がブラウザかチェック */ static isBrowser() { return typeof window !== "undefined" && typeof localStorage !== "undefined"; } /** * 実行環境がNode.jsかチェック */ static isNode() { return typeof process !== "undefined" && process.versions !== void 0 && process.versions.node !== void 0 && typeof window === "undefined"; } /** * configファイルが存在するかチェック */ static async hasConfig() { try { if (this.isBrowser()) { const config = localStorage.getItem(this.LOCAL_STORAGE_KEY); return config !== null; } if (this.isNode()) { try { const fs = await import("fs"); return fs.existsSync(this.CONFIG_FILE_PATH); } catch (fsError) { console.warn("fs module not available:", fsError); return false; } } console.warn("Unknown environment, using fallback behavior"); return false; } catch (error) { console.error("Failed to check config existence:", error); return false; } } /** * configファイルを読み込み */ static async loadConfig() { try { if (this.isBrowser()) { const configStr = localStorage.getItem(this.LOCAL_STORAGE_KEY); if (configStr) { const config = JSON.parse(configStr); return this.validateAndMigrateConfig(config); } return null; } if (this.isNode()) { try { const fs = await import("fs"); if (fs.existsSync(this.CONFIG_FILE_PATH)) { const configStr = fs.readFileSync(this.CONFIG_FILE_PATH, "utf8"); const config = JSON.parse(configStr); return this.validateAndMigrateConfig(config); } } catch (fsError) { console.warn("fs module not available:", fsError); return null; } } return null; } catch (error) { console.error("Failed to load config:", error); return null; } } /** * configファイルを保存 */ static async saveConfig(config) { try { config.lastModified = (/* @__PURE__ */ new Date()).toISOString(); const configStr = JSON.stringify(config, null, 2); if (this.isBrowser()) { localStorage.setItem(this.LOCAL_STORAGE_KEY, configStr); return true; } if (this.isNode()) { try { const fs = await import("fs"); fs.writeFileSync(this.CONFIG_FILE_PATH, configStr); return true; } catch (fsError) { console.warn("fs module not available:", fsError); return false; } } return false; } catch (error) { console.error("Failed to save config:", error); return false; } } /** * configにアクターを追加 */ static async addActor(actorData) { try { let config = await this.loadConfig(); if (!config) { config = createDefaultSDKConfig(); } config.actors[actorData.id] = { ...actorData, lastAccessed: (/* @__PURE__ */ new Date()).toISOString(), isDefault: Object.keys(config.actors).length === 0 // 最初のアクターをデフォルトに }; if (!config.defaultActorId && Object.keys(config.actors).length === 1) { config.defaultActorId = actorData.id; } config.initialized = true; return await this.saveConfig(config); } catch (error) { console.error("Failed to add actor to config:", error); return false; } } /** * デフォルトアクターを設定 */ static async setDefaultActor(actorId) { try { const config = await this.loadConfig(); if (!config || !config.actors[actorId]) { return false; } Object.values(config.actors).forEach((actor) => { actor.isDefault = false; }); config.actors[actorId].isDefault = true; config.defaultActorId = actorId; return await this.saveConfig(config); } catch (error) { console.error("Failed to set default actor:", error); return false; } } /** * アクターのアクセス時刻を更新 */ static async updateActorAccess(actorId) { try { const config = await this.loadConfig(); if (!config || !config.actors[actorId]) { return false; } config.actors[actorId].lastAccessed = (/* @__PURE__ */ new Date()).toISOString(); return await this.saveConfig(config); } catch (error) { console.error("Failed to update actor access:", error); return false; } } /** * 設定を更新 */ static async updateSettings(settings) { try { let config = await this.loadConfig(); if (!config) { config = createDefaultSDKConfig(); } config.settings = { ...config.settings, ...settings }; return await this.saveConfig(config); } catch (error) { console.error("Failed to update settings:", error); return false; } } /** * configを初期化済みにマーク */ static async markAsInitialized() { try { let config = await this.loadConfig(); if (!config) { config = createDefaultSDKConfig(); } config.initialized = true; config.settings.showWelcome = false; return await this.saveConfig(config); } catch (error) { console.error("Failed to mark as initialized:", error); return false; } } /** * configを検証・マイグレーション */ static validateAndMigrateConfig(config) { const defaultConfig = createDefaultSDKConfig(); const validatedConfig = { version: config.version || defaultConfig.version, initialized: Boolean(config.initialized), defaultActorId: config.defaultActorId, actors: config.actors || {}, settings: { theme: config.settings?.theme || defaultConfig.settings.theme, autoSave: config.settings?.autoSave !== void 0 ? config.settings.autoSave : defaultConfig.settings.autoSave, showWelcome: config.settings?.showWelcome !== void 0 ? config.settings.showWelcome : defaultConfig.settings.showWelcome, defaultView: config.settings?.defaultView || defaultConfig.settings.defaultView }, created: config.created || defaultConfig.created, lastModified: config.lastModified || defaultConfig.lastModified }; return validatedConfig; } /** * configをリセット(開発用) */ static async resetConfig() { try { if (this.isBrowser()) { localStorage.removeItem(this.LOCAL_STORAGE_KEY); return true; } if (this.isNode()) { try { const fs = await import("fs"); if (fs.existsSync(this.CONFIG_FILE_PATH)) { fs.unlinkSync(this.CONFIG_FILE_PATH); } return true; } catch (fsError) { console.warn("fs module not available:", fsError); return false; } } return false; } catch (error) { console.error("Failed to reset config:", error); return false; } } /** * デバッグ情報を出力(ブラウザのコンソールに表示) */ static async debugConfig() { try { const config = await this.loadConfig(); console.group("\u{1F527} Actor SDK Configuration Debug"); console.log("Config exists:", config !== null); console.log("Environment:", this.isBrowser() ? "Browser" : this.isNode() ? "Node.js" : "Unknown"); console.log("Storage method:", this.isBrowser() ? "localStorage" : "File System"); if (config) { console.log("Configuration:", config); console.log("Actors count:", Object.keys(config.actors).length); console.log("Default actor:", config.defaultActorId); console.log("Initialized:", config.initialized); } else { console.log("No configuration found"); } console.groupEnd(); } catch (error) { console.error("Failed to debug config:", error); } } /** * デフォルトアクターを作成 */ static async createDefaultActor(template = "chat-assistant") { try { const actorTemplate = DEFAULT_ACTOR_TEMPLATES[template]; if (!actorTemplate) { return { success: false, error: `Unknown template: ${template}` }; } const actorId = `${template}-${Math.random().toString(36).substring(2, 15)}`; const timestamp = (/* @__PURE__ */ new Date()).toISOString(); const repositoryPath = `/actors/${actorId}`; let config = await this.loadConfig(); if (!config) { config = createDefaultSDKConfig(); } config.actors[actorId] = { id: actorId, name: actorTemplate.name, type: actorTemplate.type, repositoryType: actorTemplate.repositoryType, repositoryPath, gitConfig: actorTemplate.gitConfig, lastAccessed: timestamp, isDefault: true }; config.defaultActorId = actorId; config.lastModified = timestamp; const saved = await this.saveConfig(config); if (!saved) { return { success: false, error: "Failed to save configuration" }; } console.log(`\u2705 Default actor created: ${actorTemplate.name} (${actorId})`); return { success: true, actorId }; } catch (error) { console.error("Failed to create default actor:", error); return { success: false, error: error instanceof Error ? error.message : "Unknown error" }; } } /** * 初期セットアップ - デフォルトアクターと設定を作成 */ static async performInitialSetup(actorTemplate = "chat-assistant") { try { console.log("\u{1F680} Starting initial Actor SDK setup..."); const actorResult = await this.createDefaultActor(actorTemplate); if (!actorResult.success) { return { success: false, error: actorResult.error }; } const marked = await this.markAsInitialized(); if (!marked) { return { success: false, error: "Failed to mark as initialized" }; } const config = await this.loadConfig(); if (!config) { return { success: false, error: "Failed to load configuration after setup" }; } console.log("\u2705 Initial setup completed successfully!"); return { success: true, config }; } catch (error) { console.er