@love-moon/conductor-cli 0.2.39 → 0.2.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,133 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ import yaml from "js-yaml";
6
+
7
+ export const DEFAULT_CONDUCTOR_CONFIG_BASENAME = "config.yaml";
8
+ export const DEFAULT_SERVE_AI_CONFIG_BASENAME = "config-ai-serve.yaml";
9
+
10
+ function resolvePrimaryConfigPath(configFilePath) {
11
+ if (typeof configFilePath === "string" && configFilePath.trim()) {
12
+ return path.resolve(configFilePath.trim());
13
+ }
14
+ if (typeof process.env.CONDUCTOR_CONFIG === "string" && process.env.CONDUCTOR_CONFIG.trim()) {
15
+ return path.resolve(process.env.CONDUCTOR_CONFIG.trim());
16
+ }
17
+ return path.join(os.homedir(), ".conductor", DEFAULT_CONDUCTOR_CONFIG_BASENAME);
18
+ }
19
+
20
+ export function resolveServeAiConfigPaths(configFilePath) {
21
+ const conductorConfigPath = resolvePrimaryConfigPath(configFilePath);
22
+ return {
23
+ conductorConfigPath,
24
+ serveAiConfigPath: path.join(path.dirname(conductorConfigPath), DEFAULT_SERVE_AI_CONFIG_BASENAME),
25
+ };
26
+ }
27
+
28
+ function parseYamlFile(filePath) {
29
+ const content = fs.readFileSync(filePath, "utf8");
30
+ const parsed = yaml.load(content);
31
+ if (parsed == null) {
32
+ return {};
33
+ }
34
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
35
+ throw new Error(`Expected YAML mapping in ${filePath}`);
36
+ }
37
+ return parsed;
38
+ }
39
+
40
+ export function loadServeAiRuntimeConfig(configFilePath) {
41
+ const { conductorConfigPath, serveAiConfigPath } = resolveServeAiConfigPaths(configFilePath);
42
+ const conductorExists = fs.existsSync(conductorConfigPath);
43
+ const serveAiExists = fs.existsSync(serveAiConfigPath);
44
+
45
+ let activeConfigPath = conductorConfigPath;
46
+ let source = "conductor";
47
+ if (!conductorExists && serveAiExists) {
48
+ activeConfigPath = serveAiConfigPath;
49
+ source = "serve-ai";
50
+ }
51
+
52
+ let parsed = {};
53
+ if (fs.existsSync(activeConfigPath)) {
54
+ parsed = parseYamlFile(activeConfigPath);
55
+ }
56
+
57
+ return {
58
+ conductorConfigPath,
59
+ serveAiConfigPath,
60
+ activeConfigPath,
61
+ source,
62
+ parsed,
63
+ allowCliList:
64
+ parsed && parsed.allow_cli_list && typeof parsed.allow_cli_list === "object"
65
+ ? parsed.allow_cli_list
66
+ : {},
67
+ envs:
68
+ parsed && parsed.envs && typeof parsed.envs === "object"
69
+ ? parsed.envs
70
+ : {},
71
+ defaults:
72
+ parsed && parsed.serve_ai && typeof parsed.serve_ai === "object"
73
+ ? parsed.serve_ai
74
+ : {},
75
+ };
76
+ }
77
+
78
+ function normalizeOptionalString(value) {
79
+ return typeof value === "string" && value.trim() ? value.trim() : "";
80
+ }
81
+
82
+ export function buildServeAiConfigYaml({
83
+ backend = "codex",
84
+ host = "127.0.0.1",
85
+ port = 8787,
86
+ apiKey = "",
87
+ } = {}) {
88
+ const lines = [
89
+ "# Dedicated config for `conductor serve-ai`.",
90
+ "# This file is used when the sibling config.yaml does not exist.",
91
+ "",
92
+ "serve_ai:",
93
+ ` host: ${yaml.dump(host).trim()}`,
94
+ ` port: ${Number.isFinite(Number(port)) ? Number(port) : 8787}`,
95
+ ` backend: ${yaml.dump(backend).trim()}`,
96
+ ];
97
+
98
+ const normalizedApiKey = normalizeOptionalString(apiKey);
99
+ if (normalizedApiKey) {
100
+ lines.push(` api_key: ${yaml.dump(normalizedApiKey).trim()}`);
101
+ } else {
102
+ lines.push(" # api_key: local-dev-key");
103
+ }
104
+
105
+ lines.push(
106
+ "",
107
+ "# Allowed AI backends and their launch commands.",
108
+ "allow_cli_list:",
109
+ " codex: codex",
110
+ " kimi: kimi",
111
+ " claude: claude",
112
+ " opencode: opencode",
113
+ "",
114
+ "# Optional extra environment variables for AI SDK / backend CLIs.",
115
+ "# envs:",
116
+ "# http_proxy: http://127.0.0.1:7890",
117
+ "# https_proxy: http://127.0.0.1:7890",
118
+ "# AISDK_PROVIDER_PATH: /abs/path/to/provider.js",
119
+ "",
120
+ );
121
+
122
+ return lines.join("\n");
123
+ }
124
+
125
+ export function writeServeAiConfigFile(targetPath, options = {}) {
126
+ const normalizedPath = path.resolve(String(targetPath || "").trim());
127
+ if (!normalizedPath) {
128
+ throw new Error("targetPath is required");
129
+ }
130
+ fs.mkdirSync(path.dirname(normalizedPath), { recursive: true });
131
+ fs.writeFileSync(normalizedPath, buildServeAiConfigYaml(options), "utf8");
132
+ return normalizedPath;
133
+ }
@@ -0,0 +1,28 @@
1
+ export function createOpenAiErrorBody(message, { type = "invalid_request_error", param = null, code = null } = {}) {
2
+ return {
3
+ error: {
4
+ message: String(message || "Unknown error"),
5
+ type,
6
+ param,
7
+ code,
8
+ },
9
+ };
10
+ }
11
+
12
+ export function sendJson(res, statusCode, payload, extraHeaders = {}) {
13
+ const body = JSON.stringify(payload);
14
+ res.writeHead(statusCode, {
15
+ "content-type": "application/json; charset=utf-8",
16
+ "content-length": Buffer.byteLength(body),
17
+ "cache-control": "no-store",
18
+ "access-control-allow-origin": "*",
19
+ "access-control-allow-headers": "authorization, content-type",
20
+ "access-control-allow-methods": "GET, POST, OPTIONS",
21
+ ...extraHeaders,
22
+ });
23
+ res.end(body);
24
+ }
25
+
26
+ export function sendOpenAiError(res, statusCode, message, options = {}) {
27
+ sendJson(res, statusCode, createOpenAiErrorBody(message, options));
28
+ }
@@ -0,0 +1,92 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { randomUUID } from "node:crypto";
5
+
6
+ function inferExtensionFromMimeType(mimeType) {
7
+ const normalized = String(mimeType || "").trim().toLowerCase();
8
+ if (normalized === "image/png") return ".png";
9
+ if (normalized === "image/jpeg") return ".jpg";
10
+ if (normalized === "image/webp") return ".webp";
11
+ if (normalized === "image/gif") return ".gif";
12
+ if (normalized === "image/bmp") return ".bmp";
13
+ if (normalized === "image/svg+xml") return ".svg";
14
+ return ".bin";
15
+ }
16
+
17
+ function inferExtensionFromUrl(urlString) {
18
+ try {
19
+ const pathname = new URL(urlString).pathname || "";
20
+ const ext = path.extname(pathname);
21
+ return ext || ".bin";
22
+ } catch {
23
+ return ".bin";
24
+ }
25
+ }
26
+
27
+ function parseDataUri(uri) {
28
+ const match = String(uri || "").match(/^data:([^;,]+)?(?:;charset=[^;,]+)?;base64,(.+)$/i);
29
+ if (!match) {
30
+ return null;
31
+ }
32
+ return {
33
+ mimeType: match[1] || "application/octet-stream",
34
+ data: match[2],
35
+ };
36
+ }
37
+
38
+ async function writeTempFile(buffer, extension) {
39
+ const tempDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "conductor-serve-ai-image-"));
40
+ const filePath = path.join(tempDir, `${randomUUID()}${extension || ".bin"}`);
41
+ await fs.promises.writeFile(filePath, buffer);
42
+ return {
43
+ filePath,
44
+ cleanup: async () => {
45
+ await fs.promises.rm(tempDir, { recursive: true, force: true }).catch(() => {});
46
+ },
47
+ };
48
+ }
49
+
50
+ async function materializeImageUrl(imageUrl, fetchImpl) {
51
+ const dataUri = parseDataUri(imageUrl);
52
+ if (dataUri) {
53
+ const buffer = Buffer.from(dataUri.data, "base64");
54
+ return writeTempFile(buffer, inferExtensionFromMimeType(dataUri.mimeType));
55
+ }
56
+
57
+ const response = await fetchImpl(imageUrl);
58
+ if (!response.ok) {
59
+ throw new Error(`failed to download image: HTTP ${response.status}`);
60
+ }
61
+ const arrayBuffer = await response.arrayBuffer();
62
+ const mimeType = response.headers.get("content-type") || "";
63
+ return writeTempFile(
64
+ Buffer.from(arrayBuffer),
65
+ mimeType ? inferExtensionFromMimeType(mimeType) : inferExtensionFromUrl(imageUrl),
66
+ );
67
+ }
68
+
69
+ export async function materializeImageInputs(imageUrls, { fetchImpl = fetch } = {}) {
70
+ const normalizedUrls = Array.isArray(imageUrls)
71
+ ? imageUrls.filter((item) => typeof item === "string" && item.trim()).map((item) => item.trim())
72
+ : [];
73
+ const files = [];
74
+ const cleanups = [];
75
+
76
+ try {
77
+ for (const imageUrl of normalizedUrls) {
78
+ const file = await materializeImageUrl(imageUrl, fetchImpl);
79
+ files.push(file.filePath);
80
+ cleanups.push(file.cleanup);
81
+ }
82
+ return {
83
+ files,
84
+ cleanup: async () => {
85
+ await Promise.allSettled(cleanups.map((fn) => fn()));
86
+ },
87
+ };
88
+ } catch (error) {
89
+ await Promise.allSettled(cleanups.map((fn) => fn()));
90
+ throw error;
91
+ }
92
+ }