@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,639 lines (1,631 loc) • 150 kB
JavaScript
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
if (typeof require !== "undefined") return require.apply(this, arguments);
throw Error('Dynamic require of "' + x + '" is not supported');
});
// 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
import { useState, useEffect, useCallback } from "react";
function useActorV3List(organizationId) {
const [actors, setActors] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [totalCount, setTotalCount] = useState(0);
const fetchActors = 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]);
useEffect(() => {
fetchActors();
}, [fetchActors]);
const refetch = useCallback(() => {
fetchActors();
}, [fetchActors]);
return {
actors,
loading,
error,
totalCount,
refetch
};
}
function useActorV3Creation() {
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const createActor = 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 = 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] = useState(false);
const [error, setError] = useState(null);
const [messages, setMessages] = useState([]);
const sendMessage = 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 = 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 = useCallback(() => {
setMessages([]);
}, []);
return {
sendMessage,
receiveMessages,
clearMessages,
messages,
loading,
error
};
}
function useActorV3Runnable(actorId) {
const [runnable] = useState(() => new ActorV3Runnable(actorId, actorV3Api));
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const invoke = 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 = 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] = useState(null);
const [stats, setStats] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const fetchConfig = 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 = 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 = useCallback(async () => {
await Promise.all([fetchConfig(), fetchStats()]);
}, [fetchConfig, fetchStats]);
return {
config,
stats,
loading,
error,
fetchConfig,
fetchStats,
refreshAll
};
}
function useActorV3Health() {
const [status, setStatus] = useState("unknown");
const [lastChecked, setLastChecked] = useState(null);
const [error, setError] = useState(null);
const checkHealth = 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);
}
}, []);
useEffect(() => {
checkHealth();
const interval = setInterval(checkHealth, 6e4);
return () => clearInterval(interval);
}, [checkHealth]);
return {
status,
lastChecked,
error,
checkHealth
};
}
// src/hooks/use-gftd-chat.ts
import { useState as useState2, useCallback as useCallback2, useRef, useEffect as useEffect2 } from "react";
function useGftdChat(options = {}) {
const {
initialMessages = [],
model = "gpt-3.5-turbo",
temperature = 0.7,
maxTokens = 1e3
} = options;
const [messages, setMessages] = useState2(initialMessages);
const [isLoading, setIsLoading] = useState2(false);
const [error, setError] = useState2(null);
const [isConnected, setIsConnected] = useState2(false);
const lastUserMessageRef = useRef("");
useEffect2(() => {
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 = useCallback2(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 = useCallback2(async () => {
if (lastUserMessageRef.current && !isLoading) {
await sendMessage(lastUserMessageRef.current);
}
}, [sendMessage, isLoading]);
const clearMessages = useCallback2(() => {
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.error("Failed to perform initial setup:", error);
return { success: false, error: error instanceof Error ? error.message : "Unknown error" };
}
}
/**
* 利用可能なデフォルトアクタータイプのリストを取得
*/
static getAvailableTemplates() {
return Object.entries(DEFAULT_ACTOR_TEMPLATES).map(([key, template]) => ({
key,
template
}));
}
};
SDKConfigManager.CONFIG_FILE_PATH = "/sdk.config.json";
SDKConfigManager.LOCAL_STORAGE_KEY = "actor-sdk-config";
// src/lib/git/gitlab-client.ts
import { Gitlab } from "@gitbeaker/browser";
var GitLabClient = class {
constructor(config) {
this.config = config;
this.client = new Gitlab({
host: config.url,
token: config.token
});
}
/**
* 新しいプロジェクト(Actor)を作成
* @param config プロジェクト作成設定
* @returns プロジェクト情報
*/
async createActor(config) {
try {
const project = await this.client.Projects.create({
name: config.name,
description: config.description || `Actor: ${config.name}`,
visibility: config.visibility || this.config.defaultVisibility || "private",
initialize_with_readme: config.initialize_with_readme ?? true,
default_branch: config.default_branch || "main"
});
return {
id: project.id,
name: project.name,
description: project.description,
clone_url: project.http_url_to_repo,
ssh_url: project.ssh_url_to_repo,
web_url: project.web_url,
default_branch: project.default_branch,
created_at: project.created_at
};
} catch (error) {
console.error("Failed to create actor project:", error);
throw error;
}
}
/**
* プロジェクトを取得
* @param projectId プロジェクトID
* @returns プロジェクト情報
*/
async getActor(projectId) {
try {
const project = await this.client.Projects.show(projectId);
return {
id: project.id,
name: project.name,
description: project.description,
clone_url: project.http_url_to_repo,
ssh_url: project.ssh_url_to_repo,
web_url: project.web_url,
default_branch: project.default_branch,
created_at: project.created_at,
updated_at: project.last_activity_at
};
} catch (error) {
console.error("Failed to get actor project:", error);
throw error;
}
}
/**
* 新しいブランチ(Session)を作成
* 概念: new session -> new_branch
* @param projectId プロジェクトID
* @param config ブランチ作成設定
* @returns ブランチ情報
*/
async createSession(projectId, config) {
try {
const branch = await this.client.Branches.create(projectId, config.name, config.ref);
return {
name: branch.name,
commit: {
id: branch.commit.id,
message: branch.commit.message,
author_name: branch.commit.author_name,
author_email: branch.commit.author_email,
created_at: branch.commit.created_at
},
protected: branch.protected,
can_push: branch.can_push,
web_url: branch.web_url
};
} catch (error) {
console.error("Failed to create session branch:", error);
throw error;
}
}
/**
* ブランチ(Session)を取得
* 概念: session = Git branch
* @param projectId プロジェクトID
* @param branchName ブランチ名(Session ID)
* @returns ブランチ情報
*/
async getSession(projectId, branchName) {
try {
const branch = await this.client.Branches.show(projectId, branchName);
return {
name: branch.name,
commit: {
id: branch.commit.id,
message: branch.commit.message,
author_name: branch.commit.author_name,
author_email: branch.commit.author_email,
created_at: branch.commit.created_at
},
protected: branch.protected,
can_push: branch.can_push,
web_url: branch.web_url
};
} catch (error) {
console.error("Failed to get session branch:", error);
throw error;
}
}
/**
* プロジェクトの全ブランチ(Sessions)を取得
* 概念: sessions = Git branches
* @param projectId プロジェクトID
* @returns ブランチ一覧(Session一覧)
*/
async listSessions(projectId) {
try {
const branches = await this.client.Branches.all(projectId);
return branches.map((branch) => ({
name: branch.name,
commit: {
id: branch.commit.id,
message: branch.commit.message,
author_name: branch.commit.author_name,
author_email: branch.commit.author_email,
created_at: branch.commit.created_at
},
protected: branch.protected,
can_push: branch.can_push,
web_url: branch.web_url
}));
} catch (error) {
console.error("Failed to list session branches:", error);
throw error;
}
}
/**
* ブランチを削除
* @param projectId プロジェクトID
* @param branchName ブランチ名
*/
async deleteSess