diff --git a/packages/agent-console/daemon/dist/main.js b/packages/agent-console/daemon/dist/main.js index 7dfe2b4..9482e66 100644 --- a/packages/agent-console/daemon/dist/main.js +++ b/packages/agent-console/daemon/dist/main.js @@ -4111,7 +4111,7 @@ var init_types = __esm({ // daemon/src/providers/codex/provider.ts import { homedir as homedir7 } from "node:os"; -import { join as join9 } from "node:path"; +import { dirname as dirname3, isAbsolute as isAbsolute2, join as join9 } from "node:path"; import { readFile as readFile8 } from "node:fs/promises"; function runVersion2(r, args, timeoutMs = 5e3) { return new Promise((resolvePromise, reject) => { @@ -4138,7 +4138,8 @@ function runVersion2(r, args, timeoutMs = 5e3) { function normalizeEfforts(raw) { const out = []; for (const e of raw ?? []) { - const v = typeof e === "string" ? e : e?.reasoningEffort; + const o = e; + const v = typeof e === "string" ? e : o?.reasoningEffort ?? o?.effort; if (typeof v === "string" && v && !out.includes(v)) out.push(v); } return out; @@ -4201,6 +4202,7 @@ function parseCodexConfig(text) { const profileValue = (key) => profileName ? values.get(`profiles.${profileName}\0${key}`) : void 0; const modelProvider = profileValue("model_provider") ?? top("model_provider"); const model = profileValue("model") ?? top("model"); + const catalog = profileValue("model_catalog_json") ?? top("model_catalog_json"); const provider = typeof modelProvider === "string" ? modelProvider : null; const models2 = /* @__PURE__ */ new Set(); if (typeof model === "string" && model) models2.add(model); @@ -4209,15 +4211,69 @@ function parseCodexConfig(text) { for (const m of value) models2.add(m); } } - return { modelProvider: provider, model: typeof model === "string" ? model : null, providerModels: [...models2] }; + return { + modelProvider: provider, + model: typeof model === "string" ? model : null, + providerModels: [...models2], + catalogJson: typeof catalog === "string" && catalog.trim() ? catalog.trim() : null + }; +} +function resolveCatalogPath(raw, configDir, home = homedir7()) { + let p = raw.trim(); + const env = p.match(/^(?:\$HOME|\$\{HOME\})(?=$|[\\/])/); + if (env) p = home + p.slice(env[0].length); + else if (p === "~") p = home; + else if (/^~[\\/]/.test(p)) p = join9(home, p.slice(2)); + return isAbsolute2(p) ? p : join9(configDir, p); +} +function parseCodexCatalog(text) { + const doc = JSON.parse(text); + if (!Array.isArray(doc?.models)) return []; + const out = []; + const seen = /* @__PURE__ */ new Set(); + for (const raw of doc.models) { + const m = raw; + if (!m || typeof m.slug !== "string" || !m.slug || seen.has(m.slug)) continue; + if (typeof m.visibility === "string" && m.visibility !== "list") continue; + seen.add(m.slug); + const efforts = normalizeEfforts(Array.isArray(m.supported_reasoning_levels) ? m.supported_reasoning_levels : void 0); + const thinkingOptions = efforts.map((e) => ({ id: e, label: e })); + const def = typeof m.default_reasoning_level === "string" && efforts.includes(m.default_reasoning_level) ? m.default_reasoning_level : null; + const name = typeof m.display_name === "string" && m.display_name.trim() ? m.display_name.trim() : m.slug; + out.push({ id: m.slug, name, efforts, thinkingOptions, defaultThinking: def ?? thinkingOptions[0]?.id ?? null }); + } + return out; +} +async function codexProviderModels(config, configDir, home = homedir7()) { + let rows = []; + if (config.catalogJson) { + const file = resolveCatalogPath(config.catalogJson, configDir, home); + try { + rows = parseCodexCatalog(await readFile8(file, "utf8")); + } catch (e) { + log("warn", "codex model_catalog_json \u8BFB\u53D6\u5931\u8D25", { file, err: String(e) }); + } + } + const ids = new Set(rows.map((r) => r.id)); + for (const id2 of config.providerModels) { + if (!ids.has(id2)) { + ids.add(id2); + rows.push({ id: id2, name: id2 }); + } + } + if (config.model && !rows.some((r) => r.id === config.model)) rows.unshift({ id: config.model, name: config.model }); + const def = config.model ?? rows[0]?.id; + return rows.map((r) => ({ ...r, isDefault: r.id === def })); +} +function codexConfigFile() { + const home = process.env.CODEX_HOME?.trim() || join9(homedir7(), ".codex"); + return home.toLowerCase().endsWith(".toml") ? home : join9(home, "config.toml"); } async function readCodexConfig() { - const home = process.env.CODEX_HOME?.trim() || join9(homedir7(), ".codex"); - const file = home.toLowerCase().endsWith(".toml") ? home : join9(home, "config.toml"); try { - return parseCodexConfig(await readFile8(file, "utf8")); + return parseCodexConfig(await readFile8(codexConfigFile(), "utf8")); } catch { - return { modelProvider: null, model: null, providerModels: [] }; + return { modelProvider: null, model: null, providerModels: [], catalogJson: null }; } } function isChatGptProvider(id2) { @@ -4243,7 +4299,7 @@ function createCodexProvider(version) { async listModels(launch) { const config = await readCodexConfig(); if (!isChatGptProvider(config.modelProvider)) { - const rows = config.providerModels.map((id2, i) => ({ id: id2, name: id2, isDefault: i === 0 })); + const rows = await codexProviderModels(config, dirname3(codexConfigFile())); return rows.length ? rows : [{ id: "", name: `${PLACEHOLDER_MODEL_NAME} (${config.modelProvider})`, isDefault: true }]; } if (!launch && modelCache && Date.now() - modelCache.at < MODEL_CACHE_MS) return modelCache.models; @@ -5975,7 +6031,7 @@ var init_autoApprove13 = __esm({ // daemon/src/util/mentions.ts import { realpath, stat as stat8 } from "node:fs/promises"; -import { isAbsolute as isAbsolute2, resolve as resolve3, sep as sep2, win32 as win322, posix as posix2 } from "node:path"; +import { isAbsolute as isAbsolute3, resolve as resolve3, sep as sep2, win32 as win322, posix as posix2 } from "node:path"; function insideRoot(root, child, platform = process.platform) { const p = platform === "win32" ? win322 : posix2; const norm2 = (s) => platform === "win32" ? p.resolve(s).toLowerCase() : p.resolve(s); @@ -5995,7 +6051,7 @@ async function resolveMentions(projectPath, refs) { } for (const ref of refs.slice(0, MAX_MENTIONS)) { const rel = String(ref.rel ?? "").replace(/\\/g, "/"); - if (!rel || rel.includes("\0") || isAbsolute2(rel) || /^[a-zA-Z]:/.test(rel)) { + if (!rel || rel.includes("\0") || isAbsolute3(rel) || /^[a-zA-Z]:/.test(rel)) { warnings.push(rel || "(empty)"); continue; } @@ -6834,7 +6890,7 @@ import { z } from "zod"; import { existsSync as existsSync9, statSync as statSync5 } from "node:fs"; import { mkdir as mkdir3, writeFile as writeFile4 } from "node:fs/promises"; import { homedir as homedir9 } from "node:os"; -import { dirname as dirname3, join as join12, win32 as win32Path } from "node:path"; +import { dirname as dirname4, join as join12, win32 as win32Path } from "node:path"; import { execFile as execFile4 } from "node:child_process"; function wrap(schema, fn) { return (params, ctx) => { @@ -7380,7 +7436,7 @@ function revealInFileManager(filePath) { }); return; } - execFile4("xdg-open", [dirname3(filePath)], () => { + execFile4("xdg-open", [dirname4(filePath)], () => { }).on("error", () => { }); } @@ -7418,10 +7474,10 @@ var init_methods = __esm({ // daemon/src/util/atomic.ts import { writeFile as writeFile5, rename, mkdir as mkdir4 } from "node:fs/promises"; -import { dirname as dirname4 } from "node:path"; +import { dirname as dirname5 } from "node:path"; async function writeJsonAtomic(file, obj) { try { - await mkdir4(dirname4(file), { recursive: true }); + await mkdir4(dirname5(file), { recursive: true }); const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; await writeFile5(tmp, JSON.stringify(obj, null, 2), "utf8"); await rename(tmp, file); @@ -7553,7 +7609,7 @@ var init_settings = __esm({ // daemon/src/util/jsonl.ts import { appendFile, readFile as readFile14, mkdir as mkdir5, rename as rename2, writeFile as writeFile6 } from "node:fs/promises"; -import { dirname as dirname5 } from "node:path"; +import { dirname as dirname6 } from "node:path"; async function readJsonl(file) { let text = ""; try { @@ -7576,7 +7632,7 @@ function appendJsonl(file, obj) { const prev = writers.get(file) ?? Promise.resolve(); const next = prev.then(async () => { try { - await mkdir5(dirname5(file), { recursive: true }); + await mkdir5(dirname6(file), { recursive: true }); await appendFile(file, JSON.stringify(obj) + "\n", "utf8"); } catch (e) { if (e instanceof ApiError) throw e; @@ -7865,7 +7921,7 @@ var init_warm = __esm({ // daemon/src/main.ts import { mkdirSync as mkdirSync2, rmSync as rmSync2, chmodSync as chmodSync2 } from "node:fs"; -import { join as join21, dirname as dirname8 } from "node:path"; +import { join as join21, dirname as dirname9 } from "node:path"; import { fileURLToPath as fileURLToPath4 } from "node:url"; // daemon/src/config.ts @@ -9781,7 +9837,7 @@ import { spawn as spawn4, execFileSync as execFileSync2 } from "node:child_proce import { accessSync as accessSync2, chmodSync, constants as fsc, existsSync as existsSync12, statSync as statSync7 } from "node:fs"; import { createRequire as moduleRequire } from "node:module"; import { release } from "node:os"; -import { dirname as dirname6, join as join18 } from "node:path"; +import { dirname as dirname7, join as join18 } from "node:path"; var MAX_TERMS_PER_PROJECT = 8; var BUF_MAX = 2 * 1024 * 1024; var SNAP_LINES = 5e3; @@ -9824,7 +9880,7 @@ function fixSpawnHelper() { if (process.platform !== "darwin") return; try { const req = moduleRequire(import.meta.url); - const root = dirname6(req.resolve("node-pty/package.json")); + const root = dirname7(req.resolve("node-pty/package.json")); for (const sub of [`prebuilds/darwin-${process.arch}`, "build/Release"]) { const f = join18(root, sub, "spawn-helper"); if (existsSync12(f) && !isExecFile(f)) { @@ -10079,7 +10135,7 @@ init_proxy(); // daemon/src/preview/ports.ts import { readFileSync as readFileSync2 } from "node:fs"; import { homedir as homedir10 } from "node:os"; -import { basename as basename5, dirname as dirname7, isAbsolute as isAbsolute3, join as join19 } from "node:path"; +import { basename as basename5, dirname as dirname8, isAbsolute as isAbsolute4, join as join19 } from "node:path"; import { fileURLToPath as fileURLToPath3 } from "node:url"; var MAGPIE_DEFAULT_PORTS = [3425, 3430]; var GATE_DEFAULT_PORT = 3488; @@ -10098,7 +10154,7 @@ function magpieDirFromInstall(p) { function magpieConfigDirs(env = process.env, where = {}) { const out = []; const add = (d) => { - if (d && isAbsolute3(d) && !out.includes(d)) out.push(d); + if (d && isAbsolute4(d) && !out.includes(d)) out.push(d); }; let self = where.self; if (self === void 0) { @@ -10110,9 +10166,9 @@ function magpieConfigDirs(env = process.env, where = {}) { } add(magpieDirFromInstall(self)); const cwd = where.cwd ?? (env === process.env ? process.cwd() : ""); - if (cwd && basename5(cwd) === "plugin-work") add(dirname7(cwd)); + if (cwd && basename5(cwd) === "plugin-work") add(dirname8(cwd)); const x = env.XDG_CONFIG_HOME; - if (x && isAbsolute3(x)) add(join19(x, "magpie")); + if (x && isAbsolute4(x)) add(join19(x, "magpie")); const platform = where.platform ?? process.platform; const home = where.home ?? (env === process.env ? homedir10() : platform === "win32" ? env.USERPROFILE : env.HOME); if (home) add(join19(home, ".config", "magpie")); @@ -10159,7 +10215,7 @@ if (nodeMajor < 20) { console.error(`[agent-console] \u9700\u8981 Node.js 20 \u6216\u66F4\u9AD8\u7248\u672C\uFF0C\u5F53\u524D ${process.version}\uFF08${process.execPath}\uFF09`); process.exit(3); } -process.env.PATH = augmentPath(process.env, dirname8(process.execPath)); +process.env.PATH = augmentPath(process.env, dirname9(process.execPath)); var cfg = parseConfig(process.argv.slice(2)); process.on("uncaughtException", (e) => { if (e?.code === "EPIPE") return; @@ -10173,7 +10229,7 @@ async function main() { for (const d of ["threads", "attachments", "trash", "logs"]) { mkdirSync2(join21(cfg.dataDir, d), { recursive: true }); } - const appDir = join21(dirname8(fileURLToPath4(import.meta.url)), "..", "..", "app"); + const appDir = join21(dirname9(fileURLToPath4(import.meta.url)), "..", "..", "app"); const attachments = new AttachmentStore(join21(cfg.dataDir, "attachments")); const { bindAttachmentStore: bindAttachmentStore2 } = await Promise.resolve().then(() => (init_attachmentRefs(), attachmentRefs_exports)); bindAttachmentStore2(attachments); diff --git a/packages/agent-console/daemon/dist/main.js.map b/packages/agent-console/daemon/dist/main.js.map index 4ac0411..eae5130 100644 --- a/packages/agent-console/daemon/dist/main.js.map +++ b/packages/agent-console/daemon/dist/main.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/log.ts","../src/security.ts","../src/util/i18n.ts","../src/util/paths.ts","../src/util/queue.ts","../src/agents/diff.ts","../src/providers/slash.ts","../src/providers/mock.ts","../../lib/pathscan.mjs","../src/util/gitBash.ts","../src/util/agentShell.ts","../src/util/bin.ts","../src/agents/kinds.ts","../src/providers/claude/map.ts","../src/util/attachmentRefs.ts","../src/util/attachmentKinds.ts","../src/providers/claude/content.ts","../src/providers/launch.ts","../src/util/decode.ts","../src/providers/claude/cli.ts","../src/providers/claude/session.ts","../src/providers/claude/models.ts","../src/history/import.ts","../src/providers/claude/provider.ts","../src/history/codex.ts","../src/providers/codex/rpc.ts","../src/providers/codex/input.ts","../src/providers/codex/map.ts","../src/providers/codex/commands.ts","../src/providers/codex/session.ts","../src/providers/types.ts","../src/providers/codex/provider.ts","../src/providers/catalog.ts","../src/providers/acp/spawn.ts","../src/providers/acp/clientHandlers.ts","../src/providers/acp/mapUpdate.ts","../src/providers/acp/promptCaps.ts","../src/providers/acp/sessionCaps.ts","../src/providers/acp/prompt.ts","../src/providers/acp/session.ts","../src/providers/acp/provider.ts","../src/providers/acp/dsh.ts","../src/providers/acp/probe.ts","../src/providers/acp/specs.ts","../src/providers/registry.ts","../src/providers/enabled.ts","../src/util/pickFolderWin.ts","../src/util/pickFolder.ts","../src/providers/magpieGateway.ts","../src/providers/infoCache.ts","../src/providers/modes.ts","../src/providers/autoApprove.ts","../src/migrate/autoApprove13.ts","../src/util/mentions.ts","../src/preview/url.ts","../src/util/openExternal.ts","../src/preview/inject.ts","../src/preview/proxy.ts","../src/preview/host.ts","../src/ws/methods.ts","../src/util/atomic.ts","../src/store/settings.ts","../src/util/jsonl.ts","../src/migrate/legacy.ts","../src/providers/warm.ts","../src/main.ts","../src/config.ts","../src/util/buildStamp.ts","../src/http.ts","../src/store/attachments.ts","../src/store/projects.ts","../src/store/threads.ts","../src/ws/gateway.ts","../src/agents/manager.ts","../src/timeline/coalescer.ts","../src/git/service.ts","../src/files/service.ts","../src/terminal/service.ts","../src/util/proc.ts","../src/preview/ports.ts"],"sourcesContent":["// Simple logging: writes dataDir/logs/daemon-YYYY-MM-DD.log (kept 7 days) and to the console.\nimport { appendFileSync, mkdirSync, readdirSync, rmSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nlet logDir = \"\";\nlet today = \"\";\nlet logFile = \"\";\n\nfunction fileName(d: Date): string {\n const p = (n: number) => String(n).padStart(2, \"0\");\n return `daemon-${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}.log`;\n}\n\nexport function initLog(dataDir: string): void {\n logDir = join(dataDir, \"logs\");\n mkdirSync(logDir, { recursive: true });\n // Keep 7 days\n try {\n const keep = new Set();\n const now = new Date();\n for (let i = 0; i < 7; i++) {\n keep.add(fileName(new Date(now.getTime() - i * 86400000)));\n }\n for (const f of readdirSync(logDir)) {\n if (/^daemon-\\d{4}-\\d{2}-\\d{2}\\.log$/.test(f) && !keep.has(f)) {\n rmSync(join(logDir, f), { force: true });\n }\n }\n } catch {}\n}\n\n// The console is a pipe to the plugin host. When the host is killed hard, the reader is gone and a write fails with EPIPE\n// (asynchronously, as an 'error' event on the stream): without a listener that becomes an uncaughtException. Once that happens\n// the console is dropped and only the log file is written.\nlet consoleGone = false;\nlet guarded = false;\nfunction guardConsole(): void {\n if (guarded) return;\n guarded = true;\n for (const stream of [process.stdout, process.stderr]) {\n // EPIPE, EIO, ERR_STREAM_DESTROYED…: any write error means the reader is gone; logging must never take the daemon down\n stream?.on?.(\"error\", () => { consoleGone = true; });\n }\n}\nexport function consoleClosed(): boolean {\n return consoleGone;\n}\n\nexport function log(level: \"info\" | \"warn\" | \"error\", msg: string, extra?: unknown): void {\n const line = `[${new Date().toISOString()}] [${level}] ${msg}${extra !== undefined ? \" \" + safeJson(extra) : \"\"}`;\n try {\n const d = new Date();\n const name = fileName(d);\n if (name !== today && logDir) {\n today = name;\n logFile = join(logDir, name);\n }\n if (logFile) appendFileSync(logFile, line + \"\\n\", \"utf8\");\n } catch {}\n guardConsole();\n if (consoleGone) return;\n const stream = level === \"info\" ? process.stdout : process.stderr;\n if (stream?.destroyed || stream?.writableEnded) { consoleGone = true; return; }\n const fn = level === \"error\" ? console.error : level === \"warn\" ? console.warn : console.log;\n try {\n fn(`[agent-console] ${msg}`, extra !== undefined ? extra : \"\");\n } catch {\n consoleGone = true;\n }\n}\n\nfunction safeJson(v: unknown): string {\n try {\n return JSON.stringify(v);\n } catch {\n return String(v);\n }\n}\n","// Host / Origin / token checks (timingSafeEqual).\n//\n// Security model (after the PR #535 review):\n// - Host is checked on every HTTP request and WS upgrade and must be 127.0.0.1: or localhost:,\n// to block DNS rebinding (requests from a rebound page carry no Origin, so only Host identifies them).\n// - Origin: null (opaque origin) is not trusted. Any website can send Origin: null from a sandboxed iframe, a data: or a file: page,\n// so null by itself means nothing. The token is the only authorization:\n// * token routes (/api/*, /attachments/*, WS hello) let a null origin \"present\" the token,\n// because Magpie's plugin page is a sandbox=\"allow-scripts\" iframe and can only request as null;\n// * static routes (/, app.js etc.) always 403 for null and send no CORS headers.\n// - Any other website's Origin is refused, even with the correct token.\nimport { timingSafeEqual, createHash } from \"node:crypto\";\n\nexport type CheckResult = { ok: true } | { ok: false; code: number; message: string };\n\n// none: no Origin (ordinary navigation, `;\n const head = /]*)?>/i.exec(html);\n if (head) return html.slice(0, head.index + head[0].length) + tag + html.slice(head.index + head[0].length);\n const root = /]*)?>/i.exec(html);\n if (root) return html.slice(0, root.index + root[0].length) + tag + html.slice(root.index + root[0].length);\n const doctype = /^\\s*]*>/i.exec(html);\n if (doctype) return html.slice(0, doctype[0].length) + tag + html.slice(doctype[0].length);\n return tag + html;\n}\n","// Preview proxy (1.2): a local-only reverse proxy, one 127.0.0.1: listener per loopback target origin.\n//\n// Why: Magpie's page frame is sandbox=\"allow-scripts\" and the sandbox is inherited by every child frame, so a plain\n//