244 lines
7.2 KiB
TypeScript
244 lines
7.2 KiB
TypeScript
import { loadEnvironmentFromNodeEnv } from "./common/env-loader.js";
|
|
import { getOpenRouterApiUrl, getOpenRouterEnabled, getServiceName } from "./config.js";
|
|
|
|
import type { GarnetClient } from "./common/garnet.js";
|
|
import type { NatsClient } from "./common/nats.js";
|
|
|
|
loadEnvironmentFromNodeEnv();
|
|
|
|
const { getLogger, initLogger } = await import("./observability/logger.js");
|
|
initLogger();
|
|
const logger = getLogger();
|
|
const { initTracing, shutdownTracing } = await import(
|
|
"./observability/tracing.js"
|
|
);
|
|
initTracing();
|
|
|
|
const { GarnetClient: RuntimeGarnetClient } = await import(
|
|
"./common/garnet.js"
|
|
);
|
|
const { NatsClient: RuntimeNatsClient } = await import("./common/nats.js");
|
|
const { Agent } = await import("./agent/index.js");
|
|
const { ConversationStore } = await import("./conversation/index.js");
|
|
const { OnboardingSkill } = await import("./skills/onboarding/index.js");
|
|
const { ShadowEvalBus } = await import("./eval/shadow-bus.js");
|
|
const { LlmClient } = await import("./llm/index.js");
|
|
const { getRawSecret, getSecret } = await import("./common/secret-manager.js");
|
|
const { initMongoDB, closeMongoDB } = await import("./common/mongodb.js");
|
|
const { RoomContextService } = await import("./room-context/index.js");
|
|
|
|
function firstNonEmpty(
|
|
...values: Array<string | null | undefined>
|
|
): string | undefined {
|
|
for (const value of values) {
|
|
if (value?.trim()) {
|
|
return value;
|
|
}
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
function parseEndpointList(
|
|
...values: Array<string | null | undefined>
|
|
): string[] {
|
|
const items: string[] = [];
|
|
for (const value of values) {
|
|
if (!value?.trim()) continue;
|
|
for (const item of value.split(/[\n,]/u)) {
|
|
const trimmed = item.trim();
|
|
if (trimmed) items.push(trimmed);
|
|
}
|
|
}
|
|
return [...new Set(items)];
|
|
}
|
|
|
|
function toProviderEndpoints(
|
|
urls: string[],
|
|
provider?: "llama" | "cliproxy" | "openrouter",
|
|
): Array<string | { url: string; provider?: "llama" | "cliproxy" | "openrouter" }> {
|
|
if (!provider) {
|
|
return urls;
|
|
}
|
|
return urls.map((url) => ({ url, provider }));
|
|
}
|
|
|
|
function formatEndpointList(
|
|
endpoints: Array<string | { url: string; provider?: "llama" | "cliproxy" | "openrouter" }>,
|
|
): string {
|
|
return endpoints
|
|
.map((endpoint) =>
|
|
typeof endpoint === "string"
|
|
? endpoint
|
|
: `${endpoint.provider}:${endpoint.url}`,
|
|
)
|
|
.join(", ");
|
|
}
|
|
|
|
function installShutdownHooks(
|
|
shutdown: (reason: string, error?: unknown) => Promise<void>,
|
|
): void {
|
|
let shuttingDown = false;
|
|
|
|
const runShutdown = async (
|
|
reason: string,
|
|
error?: unknown,
|
|
): Promise<void> => {
|
|
if (shuttingDown) return;
|
|
shuttingDown = true;
|
|
|
|
if (error) {
|
|
logger.error({ err: error }, `[Shutdown] ${reason}`);
|
|
} else {
|
|
logger.info(`[Shutdown] ${reason}`);
|
|
}
|
|
|
|
try {
|
|
await shutdown(reason, error);
|
|
} catch (shutdownError) {
|
|
logger.error({ err: shutdownError }, "[Shutdown] Cleanup failed");
|
|
} finally {
|
|
process.exit(error ? 1 : 0);
|
|
}
|
|
};
|
|
|
|
for (const signal of ["SIGINT", "SIGTERM"] as const) {
|
|
process.once(signal, () => {
|
|
void runShutdown(signal);
|
|
});
|
|
}
|
|
|
|
process.once("uncaughtException", (error) => {
|
|
void runShutdown("uncaughtException", error);
|
|
});
|
|
|
|
process.once("unhandledRejection", (reason) => {
|
|
void runShutdown("unhandledRejection", reason);
|
|
});
|
|
}
|
|
|
|
async function bootstrap(): Promise<void> {
|
|
const serviceName = getServiceName();
|
|
|
|
const natsClient: NatsClient = new RuntimeNatsClient();
|
|
await natsClient.connect();
|
|
|
|
const garnetClient: GarnetClient = new RuntimeGarnetClient();
|
|
await garnetClient.connect();
|
|
|
|
// LLM Client setup
|
|
const cliProxyEndpoints = parseEndpointList(
|
|
getRawSecret("CLI_PROXY_API_URLS"),
|
|
process.env["CLI_PROXY_API_URLS"],
|
|
);
|
|
const generalLlmEndpoints = parseEndpointList(
|
|
getRawSecret("AGENT_LLM_API_URLS"),
|
|
process.env["AGENT_LLM_API_URLS"],
|
|
getRawSecret("LLAMA_SERVER_API_URL"),
|
|
process.env["LLAMA_SERVER_API_URL"],
|
|
);
|
|
const openRouterEndpoints = getOpenRouterEnabled()
|
|
? parseEndpointList(
|
|
getRawSecret("OPENROUTER_API_URL"),
|
|
process.env["OPENROUTER_API_URL"],
|
|
getOpenRouterApiUrl(),
|
|
)
|
|
: [];
|
|
const llmEndpoints = [
|
|
...toProviderEndpoints(cliProxyEndpoints, "cliproxy"),
|
|
...toProviderEndpoints(openRouterEndpoints, "openrouter"),
|
|
...toProviderEndpoints(generalLlmEndpoints, "llama"),
|
|
];
|
|
const cliproxyApiKey = firstNonEmpty(
|
|
getRawSecret("CLI_PROXY_API_KEY"),
|
|
process.env["CLI_PROXY_API_KEY"],
|
|
);
|
|
const openRouterApiKey = firstNonEmpty(
|
|
getRawSecret("OPENROUTER_API_KEY"),
|
|
process.env["OPENROUTER_API_KEY"],
|
|
);
|
|
const llmApiKey = firstNonEmpty(
|
|
getRawSecret("AGENT_LLM_API_KEY"),
|
|
process.env["AGENT_LLM_API_KEY"],
|
|
getRawSecret("LLAMA_SERVER_API_KEY"),
|
|
process.env["LLAMA_SERVER_API_KEY"],
|
|
);
|
|
const llmModel = firstNonEmpty(
|
|
getRawSecret("AGENT_LLM_MODEL"),
|
|
process.env["AGENT_LLM_MODEL"],
|
|
);
|
|
const providerApiKeys = Object.fromEntries(
|
|
[
|
|
["cliproxy", cliproxyApiKey],
|
|
["llama", llmApiKey],
|
|
["openrouter", openRouterApiKey],
|
|
].filter((entry): entry is [string, string] => typeof entry[1] === "string"),
|
|
) as Partial<Record<"cliproxy" | "llama" | "openrouter", string>>;
|
|
|
|
const llmClient = new LlmClient({
|
|
endpoints: llmEndpoints,
|
|
garnetClient,
|
|
apiKey: llmApiKey,
|
|
model: llmModel,
|
|
providerApiKeys,
|
|
});
|
|
|
|
if (llmEndpoints.length > 0) {
|
|
logger.info(
|
|
{ endpoints: formatEndpointList(llmEndpoints) },
|
|
"✓ LLM endpoints configured",
|
|
);
|
|
} else {
|
|
logger.warn("[LLM] No endpoints configured — all responses will use templates");
|
|
}
|
|
|
|
// MongoDB + RoomContextService setup (optional)
|
|
let roomContextService: InstanceType<typeof RoomContextService> | undefined;
|
|
const mongoConnectionString = firstNonEmpty(
|
|
getSecret("MONGODB_CONNECTION_STRING"),
|
|
process.env["MONGODB_CONNECTION_STRING"],
|
|
);
|
|
if (mongoConnectionString) {
|
|
await initMongoDB(mongoConnectionString);
|
|
// 시크릿의 projectId를 환경변수로 전파 (config.ts에서 참조)
|
|
const mongoProjectId = firstNonEmpty(
|
|
getSecret("MONGODB_PROJECT_ID"),
|
|
process.env["MONGODB_PROJECT_ID"],
|
|
);
|
|
if (mongoProjectId) {
|
|
process.env["MONGODB_PROJECT_ID"] = mongoProjectId;
|
|
}
|
|
roomContextService = new RoomContextService();
|
|
logger.info("✓ MongoDB connected (room context enabled)");
|
|
} else {
|
|
logger.warn("[MongoDB] No connection string configured — room context disabled");
|
|
}
|
|
|
|
// Agent setup
|
|
const conversationStore = new ConversationStore(garnetClient);
|
|
const agent = new Agent(natsClient, conversationStore);
|
|
|
|
// Register skills
|
|
const shadowEvalBus = new ShadowEvalBus(garnetClient);
|
|
const onboardingSkill = new OnboardingSkill(garnetClient, llmClient, roomContextService, shadowEvalBus);
|
|
agent.registerSkill(onboardingSkill);
|
|
|
|
installShutdownHooks(async () => {
|
|
await natsClient.close();
|
|
await garnetClient.close();
|
|
await closeMongoDB();
|
|
await shutdownTracing();
|
|
});
|
|
|
|
await agent.start();
|
|
|
|
logger.info(`✓ ${serviceName} bootstrapped`);
|
|
}
|
|
|
|
try {
|
|
await bootstrap();
|
|
} catch (error) {
|
|
logger.error({ err: error }, "[Bootstrap] Fatal startup error");
|
|
await shutdownTracing();
|
|
process.exitCode = 1;
|
|
}
|