@xcanwin/manyoyo 8.7.0 → 8.7.2

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.
package/README.md CHANGED
@@ -54,7 +54,7 @@ manyoyo init all # 把本机已有的 Agent 配置搬进来
54
54
  manyoyo run -y c # 在沙箱里以 YOLO 模式启动 Claude Code
55
55
  ```
56
56
 
57
- 默认镜像 `ghcr.io/xcanwin/manyoyo` 首次使用时自动拉取;需要自定义镜像时再执行 `manyoyo build --iv 2.3.0-common`。更多命令见[命令速查](https://xcanwin.github.io/manyoyo/reference/cli-options)。
57
+ 默认镜像 `ghcr.io/xcanwin/manyoyo` 首次使用时自动拉取;需要自定义镜像时再执行 `manyoyo build --iv 2.3.1-common`。更多命令见[命令速查](https://xcanwin.github.io/manyoyo/reference/cli-options)。
58
58
 
59
59
  ## 它能做什么
60
60
 
@@ -110,7 +110,7 @@ manyoyo init all # import the agent configs already on this machine
110
110
  manyoyo run -y c # start Claude Code in YOLO mode inside the sandbox
111
111
  ```
112
112
 
113
- The default image `ghcr.io/xcanwin/manyoyo` is pulled automatically on first use; run `manyoyo build --iv 2.3.0-common` only if you need a custom image. More commands: [CLI reference](https://xcanwin.github.io/manyoyo/en/reference/cli-options).
113
+ The default image `ghcr.io/xcanwin/manyoyo` is pulled automatically on first use; run `manyoyo build --iv 2.3.1-common` only if you need a custom image. More commands: [CLI reference](https://xcanwin.github.io/manyoyo/en/reference/cli-options).
114
114
 
115
115
  ## What it does
116
116
 
@@ -14,15 +14,15 @@
14
14
  "hooks": [
15
15
  {
16
16
  "type": "command",
17
- "command": "[ \"$CLAUDE_CODE_ENTRYPOINT\" = cli ] || exit 0; sleep 0; printf '%s' '{\"terminalSequence\":\"\\u0007\"}'"
17
+ "command": "[ \"$CLAUDE_CODE_ENTRYPOINT\" = cli ] || exit 0; case \"$MANYOYO_CLAUDE_BELL\" in 0) exit 0;; esac; sleep 0; printf '%s' '{\"terminalSequence\":\"\\u0007\"}'"
18
18
  },
19
19
  {
20
20
  "type": "command",
21
- "command": "[ \"$CLAUDE_CODE_ENTRYPOINT\" = cli ] || exit 0; sleep 0.3; printf '%s' '{\"terminalSequence\":\"\\u0007\"}'"
21
+ "command": "[ \"$CLAUDE_CODE_ENTRYPOINT\" = cli ] || exit 0; case \"$MANYOYO_CLAUDE_BELL\" in 0|1) exit 0;; esac; sleep 0.3; printf '%s' '{\"terminalSequence\":\"\\u0007\"}'"
22
22
  },
23
23
  {
24
24
  "type": "command",
25
- "command": "[ \"$CLAUDE_CODE_ENTRYPOINT\" = cli ] || exit 0; sleep 0.6; printf '%s' '{\"terminalSequence\":\"\\u0007\"}'"
25
+ "command": "[ \"$CLAUDE_CODE_ENTRYPOINT\" = cli ] || exit 0; case \"$MANYOYO_CLAUDE_BELL\" in 0|1) exit 0;; esac; sleep 0.6; printf '%s' '{\"terminalSequence\":\"\\u0007\"}'"
26
26
  }
27
27
  ]
28
28
  }
@@ -41,24 +41,41 @@ function resolveYoloCommand(yolo) {
41
41
  return adapter.yoloCommand;
42
42
  }
43
43
 
44
- // Codex 0.160 / 0.164 实测不认环境变量 OPENAI_BASE_URL,只认 `-c openai_base_url=...`。
45
- // 向导给 Codex 配“兼容服务”写的是环境变量,所以执行 codex 的命令要在容器里由 shell 展开出 -c:
46
- // 变量没设就一个参数都不多;地址只在容器里从环境变量读,不拼进命令文本(也就不会出现在日志和 ps 里)。
47
- // 只处理以 codex 开头(可带前置的 KEY=值)的命令;命令里已经写了 openai_base_url 就以用户的为准。
44
+ // Codex 0.164 实测:`exec` 不认环境变量 OPENAI_BASE_URL,也不读 OPENAI_API_KEY(DeepSeek 返回 401),
45
+ // 也不读 OPENAI_MODEL;要用自定义 model_provider(env_key 指定读哪个变量,wire_api=responses)。
46
+ // 向导给 Codex 配“兼容服务”写的是环境变量,所以执行 codex 的命令要在容器里由 shell 展开成 -c / --model:
47
+ // 变量没设就一个参数都不多;值只在容器里从环境变量读,不拼进命令文本(也就不会出现在日志和 ps 里)。
48
+ // 只处理以 codex 开头(可带前置的 KEY=值)的命令;命令里已经写了 openai_base_url / model_provider 就以用户的为准。
49
+ // 只有地址没有 OPENAI_API_KEY 时(Codex 用 ChatGPT 登录、地址指向 chatgpt.com 的后端)走内置 provider 换地址的老办法;
50
+ // 两个都有才用自定义 provider。老写法总是带上(对自定义 provider 无影响),这样没有 Key 的老配置不退化。
48
51
  const CODEX_BASE_URL_FLAGS = '${OPENAI_BASE_URL:+-c "openai_base_url=\\"$OPENAI_BASE_URL\\""}';
52
+ const CODEX_PROVIDER_FLAGS = '${OPENAI_BASE_URL:+${OPENAI_API_KEY:+-c model_provider=manyoyo -c model_providers.manyoyo.name=manyoyo -c "model_providers.manyoyo.base_url=\\"$OPENAI_BASE_URL\\"" -c model_providers.manyoyo.env_key=OPENAI_API_KEY -c model_providers.manyoyo.wire_api=responses}}';
53
+ const CODEX_MODEL_FLAGS = '${OPENAI_MODEL:+--model "$OPENAI_MODEL"}';
49
54
  // 有 exec / exec resume 子命令时插在它们后面(codex exec -c … --json …),保持 `codex exec` 连在一起
50
55
  const CODEX_COMMAND_START = /^((?:\s*[A-Za-z_][A-Za-z0-9_]*=(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|[^\s]*)\s+)*\s*)codex(?:\s+exec(?:\s+resume)?)?(?=\s|$)/;
56
+ // codex 不允许 --model 出现两次,命令里已经指定了模型(会话里选的)就不再追加环境变量里的
57
+ const CODEX_HAS_MODEL = /(?:^|\s)(?:--model|-m)(?:[\s=]|$)|(?:^|\s)model=/;
51
58
 
59
+ // 我们自己拼进命令的系统说明(-c 'developer_instructions=…')里有任意文字,判断“用户有没有写过”时要先去掉
60
+ const CODEX_INSTRUCTIONS_FLAG = /-c\s+'developer_instructions=(?:[^']|'\\'')*'/g;
61
+
62
+ // 传入的应该是还带着 {prompt} 占位的模板(或没有提示词的命令):渲染进提示词之后再调用,用户的提示词会干扰“已经写过”的判断
52
63
  function withCodexBaseUrl(command) {
53
64
  const text = String(command || '');
54
- if (!text || /openai_base_url/.test(text)) return text;
65
+ if (!text) return text;
55
66
  const match = text.match(CODEX_COMMAND_START);
56
67
  if (!match) return text;
57
- return `${match[0]} ${CODEX_BASE_URL_FLAGS}${text.slice(match[0].length)}`;
68
+ const detect = text.replace(CODEX_INSTRUCTIONS_FLAG, ' ');
69
+ const parts = [];
70
+ if (!/openai_base_url|model_provider/.test(detect)) parts.push(CODEX_BASE_URL_FLAGS, CODEX_PROVIDER_FLAGS);
71
+ if (!CODEX_HAS_MODEL.test(detect)) parts.push(CODEX_MODEL_FLAGS);
72
+ if (!parts.length) return text;
73
+ return `${match[0]} ${parts.join(' ')}${text.slice(match[0].length)}`;
58
74
  }
59
75
 
60
76
  module.exports = {
61
77
  AGENT_ADAPTERS,
78
+ findAdapterByAlias,
62
79
  resolveYoloCommand,
63
80
  withCodexBaseUrl
64
81
  };
@@ -35,6 +35,51 @@ run_autostart() {
35
35
  log "自启动脚本退出,退出码 $?"
36
36
  }
37
37
 
38
+ # trust_workdir:预先信任容器的工作目录,交互式 claude / codex 首次启动不再停在“信任此文件夹”。
39
+ # 任何失败都静默,不影响 init。目录只经环境变量传给 node,不拼进脚本文本。
40
+ # BEGIN trust_workdir
41
+ trust_workdir() {
42
+ local dir
43
+ dir=$(pwd -P 2>/dev/null) || return 0
44
+ [ -n "$dir" ] || return 0
45
+ if [ -f "$HOME/.claude.json" ] && command -v node >/dev/null 2>&1; then
46
+ TRUST_DIR="$dir" node -e '
47
+ const fs = require("fs");
48
+ const file = process.env.HOME + "/.claude.json";
49
+ const dir = process.env.TRUST_DIR;
50
+ let data;
51
+ try { data = JSON.parse(fs.readFileSync(file, "utf8")); } catch (e) { process.exit(0); }
52
+ if (!data || typeof data !== "object" || Array.isArray(data)) process.exit(0);
53
+ if (!data.projects || typeof data.projects !== "object") data.projects = {};
54
+ const project = data.projects[dir] && typeof data.projects[dir] === "object" ? data.projects[dir] : {};
55
+ if (project.hasTrustDialogAccepted === true) process.exit(0);
56
+ project.hasTrustDialogAccepted = true;
57
+ data.projects[dir] = project;
58
+ const text = JSON.stringify(data, null, 2);
59
+ const tmp = file + ".manyoyo-tmp";
60
+ try {
61
+ fs.writeFileSync(tmp, text, { mode: fs.statSync(file).mode & 0o777 });
62
+ fs.renameSync(tmp, file);
63
+ } catch (e) {
64
+ // 目录不可写或文件是单独挂进来的(rename 会失败):直接原地写
65
+ try { fs.unlinkSync(tmp); } catch (e2) {}
66
+ fs.writeFileSync(file, text);
67
+ }
68
+ ' >/dev/null 2>&1
69
+ fi
70
+ if [ -f "$HOME/.codex/config.toml" ]; then
71
+ case "$dir" in
72
+ *[\"\\]*|*[[:cntrl:]]*) return 0 ;;
73
+ esac
74
+ # 已经有这个目录的 [projects.…] 表(写法可能不同:单引号、行尾注释)就不再追加,重复的表会让 codex 解析配置失败
75
+ grep -F "$dir" "$HOME/.codex/config.toml" 2>/dev/null | grep -q '^[[:space:]]*\[projects\.' \
76
+ || printf '\n[projects."%s"]\ntrust_level = "trusted"\n' "$dir" >> "$HOME/.codex/config.toml" 2>/dev/null
77
+ fi
78
+ return 0
79
+ }
80
+ # END trust_workdir
81
+ (trust_workdir) >/dev/null 2>&1 &
82
+
38
83
  setsid bash -c "$(declare -f log load_env run_autostart); BOX=$BOX SYS=$SYS GATE=$GATE LOG=$LOG; run_autostart" >/dev/null 2>&1 &
39
84
 
40
85
  while :; do sleep 3600 & wait $!; done
package/lib/image-pull.js CHANGED
@@ -39,6 +39,26 @@ function pullImageProcess(options) {
39
39
  });
40
40
  }
41
41
 
42
+ // 镜像拉不到时给网页弹窗用的结构化信息:判断用的是系统 docker / 系统 podman / 自带的私有 podman,
43
+ // 给出对应的一条在线拉取命令和一条本地构建命令(命令里的镜像引用和版本都来自 imageRef,已经是校验过的名字)
44
+ function describeImageProblem(imageRef, dockerCmd) {
45
+ const cmd = String(dockerCmd || '');
46
+ const base = cmd.split('/').pop();
47
+ const isPrivate = /[\\/]\.manyoyo[\\/]runtime[\\/]podman[\\/]/.test(cmd);
48
+ const runtime = isPrivate ? 'private-podman' : (base === 'podman' ? 'podman' : 'docker');
49
+ const labels = { 'private-podman': 'MANYOYO 自带的 Podman', podman: '系统的 Podman', docker: '系统的 Docker' };
50
+ const pullCommand = isPrivate ? `my podman pull ${imageRef}` : `${runtime} pull ${imageRef}`;
51
+ const tag = String(imageRef || '').split(':').pop();
52
+ const version = /^\d+\.\d+\.\d+-[A-Za-z0-9][A-Za-z0-9._-]*$/.test(tag) ? tag : '<x.y.z-后缀>';
53
+ return {
54
+ imageRef,
55
+ runtime,
56
+ runtimeLabel: labels[runtime],
57
+ pullCommand,
58
+ buildCommand: `my build --iv ${version}`
59
+ };
60
+ }
61
+
42
62
  function toFriendlyPullError(error, imageRef, command) {
43
63
  const text = `${error && error.output || ''}\n${error && error.message || ''}`;
44
64
  const info = describeError(text, { imageRef, command });
@@ -46,6 +66,9 @@ function toFriendlyPullError(error, imageRef, command) {
46
66
  ? `${info.reason}\n${info.action}`
47
67
  : `拉取镜像 ${imageRef} 失败: ${String(error && error.message || error).split('\n')[0]}`);
48
68
  friendly.code = info ? info.code : 'IMAGE_PULL_FAILED';
69
+ if (friendly.code === 'IMAGE_NOT_FOUND' || friendly.code === 'IMAGE_PULL_FAILED') {
70
+ friendly.imageProblem = { code: friendly.code, ...describeImageProblem(imageRef, command) };
71
+ }
49
72
  friendly.cause = error;
50
73
  return friendly;
51
74
  }
@@ -70,6 +93,7 @@ async function ensureImagePresent(options) {
70
93
  }
71
94
 
72
95
  module.exports = {
96
+ describeImageProblem,
73
97
  pullImageProcess,
74
98
  toFriendlyPullError,
75
99
  ensureImagePresent
@@ -22,10 +22,13 @@ const AGENT_ENV_SCHEMA = {
22
22
  { name: 'CLAUDE_CODE_OAUTH_TOKEN', description: 'Claude Code OAuth 令牌(订阅登录)', secret: true },
23
23
  { name: 'ANTHROPIC_BASE_URL', description: 'API 地址(使用官方服务可留空)', secret: false },
24
24
  { name: 'ANTHROPIC_MODEL', description: '默认模型', secret: false },
25
- { name: 'ANTHROPIC_DEFAULT_OPUS_MODEL', description: 'Opus 档位对应的模型', secret: false },
26
- { name: 'ANTHROPIC_DEFAULT_SONNET_MODEL', description: 'Sonnet 档位对应的模型', secret: false },
27
- { name: 'ANTHROPIC_DEFAULT_HAIKU_MODEL', description: 'Haiku 档位对应的模型', secret: false },
28
- { name: 'CLAUDE_CODE_SUBAGENT_MODEL', description: '子 Agent 使用的模型', secret: false }
25
+ { name: 'ANTHROPIC_DEFAULT_FABLE_MODEL', description: '顶级模型(Fable)对应的模型', secret: false },
26
+ { name: 'ANTHROPIC_DEFAULT_OPUS_MODEL', description: '高级模型(Opus)对应的模型', secret: false },
27
+ { name: 'ANTHROPIC_DEFAULT_SONNET_MODEL', description: '标准模型(Sonnet)对应的模型', secret: false },
28
+ { name: 'ANTHROPIC_DEFAULT_HAIKU_MODEL', description: '轻量模型(Haiku)对应的模型', secret: false },
29
+ { name: 'CLAUDE_CODE_SUBAGENT_MODEL', description: '子 Agent 使用的模型', secret: false },
30
+ { name: 'CLAUDE_CODE_AUTO_COMPACT_WINDOW', description: '上下文到多少才自动压缩', secret: false },
31
+ { name: 'ENABLE_TOOL_SEARCH', description: '工具搜索(部分兼容服务要设为 false,否则模型调不了工具)', secret: false }
29
32
  ]
30
33
  },
31
34
  codex: {
@@ -481,6 +484,8 @@ async function initAgentConfigs(rawAgents, options = {}) {
481
484
 
482
485
  module.exports = {
483
486
  initAgentConfigs,
487
+ collectClaudeInitData,
488
+ collectCodexInitData,
484
489
  AGENT_ENV_SCHEMA,
485
490
  agentEnvKeys
486
491
  };
@@ -224,6 +224,56 @@ function findTopLevelPropertyValueRange(text, propertyName) {
224
224
  return findValueRangeByPath(text, [propertyName]);
225
225
  }
226
226
 
227
+ // 按路径删除一个属性(连同它所在行和行尾 // 注释);路径不存在就原样返回。
228
+ // 删掉最后一个属性时前一项的逗号会留下成为尾逗号,JSON5 允许。
229
+ function removeValueByPath(text, pathParts) {
230
+ if (!Array.isArray(pathParts) || pathParts.length === 0) {
231
+ throw new Error('path 不能为空');
232
+ }
233
+ let objectStart = findRootObjectStart(text);
234
+ if (objectStart === -1) return text;
235
+ for (let i = 0; i < pathParts.length - 1; i += 1) {
236
+ const range = findObjectPropertyValueRange(text, objectStart, pathParts[i]);
237
+ if (!range) return text;
238
+ const next = skipTrivia(text, range.start);
239
+ if (text[next] !== '{') return text;
240
+ objectStart = next;
241
+ }
242
+ const target = pathParts[pathParts.length - 1];
243
+ let cursor = skipTrivia(text, objectStart + 1);
244
+ while (cursor < text.length) {
245
+ cursor = skipTrivia(text, cursor);
246
+ if (text[cursor] === '}') return text;
247
+ const keyStart = cursor;
248
+ const token = readPropertyToken(text, cursor);
249
+ if (!token) return text;
250
+ cursor = skipTrivia(text, token.end);
251
+ if (text[cursor] !== ':') return text;
252
+ const valueStart = skipTrivia(text, cursor + 1);
253
+ const valueEnd = scanValueEnd(text, valueStart);
254
+ if (token.value === target) {
255
+ let end = valueEnd;
256
+ while (text[end] === ' ' || text[end] === '\t') end += 1;
257
+ if (text[end] === ',') end += 1;
258
+ while (text[end] === ' ' || text[end] === '\t') end += 1;
259
+ if (text[end] === '/' && text[end + 1] === '/') {
260
+ while (end < text.length && text[end] !== '\n') end += 1;
261
+ }
262
+ const lineStart = text.lastIndexOf('\n', keyStart - 1) + 1;
263
+ const onOwnLine = /^[ \t]*$/.test(text.slice(lineStart, keyStart));
264
+ if (onOwnLine && text[end] === '\n') end += 1;
265
+ return `${text.slice(0, onOwnLine ? lineStart : keyStart)}${text.slice(end)}`;
266
+ }
267
+ cursor = skipTrivia(text, valueEnd);
268
+ if (text[cursor] === ',') {
269
+ cursor += 1;
270
+ continue;
271
+ }
272
+ return text;
273
+ }
274
+ return text;
275
+ }
276
+
227
277
  function applyTextReplacements(text, replacements) {
228
278
  return replacements
229
279
  .slice()
@@ -313,5 +363,6 @@ module.exports = {
313
363
  findTopLevelPropertyValueRange,
314
364
  findValueRangeByPath,
315
365
  applyTextReplacements,
366
+ removeValueByPath,
316
367
  upsertValueByPath
317
368
  };
@@ -0,0 +1,63 @@
1
+ 'use strict';
2
+
3
+ // 模型服务改了 Key / 地址 / 模型后,已有容器的 box/env 里还是创建时写进去的旧值。
4
+ // 这里按“env 里的 Key 等于旧 Key”找出还在用它的容器,并把新值写进它们的 box/env(每次 exec 都会重新读,下一轮对话生效,不用重建)。
5
+ // 只改指定的几个变量(整行替换,没有就追加,要删的删掉),其余行和注释原样保留。
6
+ const state = require('./container-state');
7
+ const { formatEnvValue, parseEnvText } = require('./env-text');
8
+ const { parseEnvEntry } = require('./runtime-normalizers');
9
+
10
+ /**
11
+ * containers:[{ name, id }](受管容器);返回 box/env 里 keyEnv 的值等于 keyValue 的那些。
12
+ * 服务有地址时容器里的地址也要相同:同一个 Key 常被用在不同的服务上(比如 Claude 和 Codex,或两个模型),不能误伤。
13
+ */
14
+ function findUsingContainers({ homeDir, containers, keyEnv, keyValue, baseUrlKey, baseUrl }) {
15
+ if (!keyEnv || !keyValue) return [];
16
+ return containers.filter(item => {
17
+ if (!state.stateExists(homeDir, item.id)) return false;
18
+ const { entries } = parseEnvText(state.readEnv(homeDir, item.id).text);
19
+ if (!entries.some(entry => entry.key === keyEnv && entry.value === keyValue)) return false;
20
+ return !baseUrlKey || !baseUrl || entries.some(entry => entry.key === baseUrlKey && entry.value === baseUrl);
21
+ });
22
+ }
23
+
24
+ /** 返回改写后的 env 文本;set:{ KEY: 新值 },remove:[KEY…] */
25
+ function rewriteEnvText(text, { set = {}, remove = [] }) {
26
+ const lines = String(text || '').split('\n');
27
+ const { entries } = parseEnvText(text);
28
+ const handled = new Set();
29
+ const drop = new Set();
30
+ entries.forEach(entry => {
31
+ if (Object.prototype.hasOwnProperty.call(set, entry.key)) {
32
+ lines[entry.line - 1] = `${entry.key}=${formatEnvValue(String(set[entry.key]))}`;
33
+ handled.add(entry.key);
34
+ } else if (remove.includes(entry.key)) {
35
+ drop.add(entry.line - 1);
36
+ }
37
+ });
38
+ let out = lines.filter((_, index) => !drop.has(index)).join('\n');
39
+ const missing = Object.keys(set).filter(key => !handled.has(key));
40
+ if (missing.length) {
41
+ if (out && !out.endsWith('\n')) out += '\n';
42
+ out += missing.map(key => `${key}=${formatEnvValue(String(set[key]))}`).join('\n');
43
+ }
44
+ return out && !out.endsWith('\n') ? `${out}\n` : out;
45
+ }
46
+
47
+ function applyToContainers({ homeDir, targets, set, remove }) {
48
+ const updated = [];
49
+ for (const item of targets) {
50
+ const current = state.readEnv(homeDir, item.id);
51
+ // 读到的 etag 随写随比,容器里同时改过就跳过这一个,不覆盖别人的修改
52
+ // 配置已经保存,一个容器写失败(冲突、写不进)只跳过它,不能让整个请求报错
53
+ try {
54
+ state.writeEnv(homeDir, item.id, rewriteEnvText(current.text, { set, remove }), { ifMatch: current.etag, parseEnvEntry });
55
+ updated.push(item.name);
56
+ } catch (e) {
57
+ // 跳过
58
+ }
59
+ }
60
+ return updated;
61
+ }
62
+
63
+ module.exports = { findUsingContainers, rewriteEnvText, applyToContainers };
@@ -0,0 +1,98 @@
1
+ 'use strict';
2
+
3
+ // 「从本机导入」:把本机已有的 Claude / Codex 的 Key、地址、模型读出来,让用户预览后写成模型服务。
4
+ // 数据源与 `manyoyo init` 相同(环境变量、~/.claude/settings.json 的 env、~/.codex 的 OPENAI_API_KEY 与 config.toml),
5
+ // 但只提取 Key / 地址 / 模型,不加任何挂载(init 会把整个 ~/.codex 读写挂进容器),也不碰 OAuth 登录凭据。
6
+ const { AGENT_ENV_SCHEMA, collectClaudeInitData, collectCodexInitData } = require('./init-config');
7
+ const { findProviderByBaseUrl } = require('./provider-presets');
8
+ const { listModelServices, keyValueOf, uniqueRunName, keyTail, agentLabelOf } = require('./model-services');
9
+ const { buildAgentRunProfile } = require('./setup');
10
+
11
+ const IMPORT_AGENTS = [
12
+ { id: 'claude', collect: collectClaudeInitData, sources: '环境变量、~/.claude/settings.json' },
13
+ { id: 'codex', collect: collectCodexInitData, sources: '环境变量、~/.codex/auth.json、~/.codex/config.toml' }
14
+ ];
15
+
16
+ // 读不了文件时只当没有,不往终端打印
17
+ const SILENT_CTX = { colors: { YELLOW: '', NC: '' }, log: () => {} };
18
+
19
+ /**
20
+ * 扫描本机,返回候选(含内部 env,调用方不能原样下发给前端)。
21
+ * 每个候选:{ id, agent, env, baseUrl, model, secret, duplicate, invalid }
22
+ */
23
+ function scanLocalServices(homeDir, config) {
24
+ const existing = listModelServices(config);
25
+ const existingKeys = new Set(existing.map(item => `${item.agent}|${keyValueOf(config, item.name)}`));
26
+ const candidates = [];
27
+ for (const agent of IMPORT_AGENTS) {
28
+ const spec = AGENT_ENV_SCHEMA[agent.id];
29
+ const { values } = agent.collect(homeDir, SILENT_CTX);
30
+ const env = {};
31
+ for (const item of spec.env) {
32
+ const value = values[item.name];
33
+ // OAuth 令牌不导入:订阅登录只做引导
34
+ if (item.name.includes('OAUTH')) continue;
35
+ if (typeof value === 'string' && value.trim()) env[item.name] = value.trim();
36
+ }
37
+ const keyName = spec.requiredAnyOf.find(name => env[name]);
38
+ if (!keyName) continue;
39
+ const secret = env[keyName];
40
+ let invalid = '';
41
+ try {
42
+ buildAgentRunProfile(agent.id, env, {});
43
+ // Codex 不会从环境变量读默认模型,有地址没模型的配置导入后请求会直接报错
44
+ if (agent.id === 'codex' && env[spec.baseUrlKey] && !env[spec.modelKey]) throw new Error('Codex CLI 接兼容服务必须指定模型');
45
+ } catch (e) {
46
+ invalid = e.message;
47
+ }
48
+ candidates.push({
49
+ id: agent.id,
50
+ agent: agent.id,
51
+ env,
52
+ secret,
53
+ baseUrl: env[spec.baseUrlKey] || '',
54
+ model: env[spec.modelKey] || '',
55
+ duplicate: existingKeys.has(`${agent.id}|${secret}`),
56
+ invalid
57
+ });
58
+ }
59
+ return candidates;
60
+ }
61
+
62
+ /** 给前端预览用:只有 Key 末 4 位,没有 env 原文 */
63
+ function toPreview(candidates) {
64
+ return candidates.map(item => {
65
+ const provider = findProviderByBaseUrl(item.agent, item.baseUrl);
66
+ return {
67
+ id: item.id,
68
+ agent: item.agent,
69
+ agentLabel: agentLabelOf(item.agent),
70
+ providerLabel: provider ? provider.label : (item.baseUrl ? '自定义地址' : '官方'),
71
+ baseUrl: item.baseUrl,
72
+ model: item.model,
73
+ keyTail: keyTail(item.secret),
74
+ duplicate: item.duplicate,
75
+ invalid: item.invalid
76
+ };
77
+ });
78
+ }
79
+
80
+ /** 把选中的候选变成要写入的 [{ name, profile }];名字冲突就加数字,绝不覆盖已有的运行配置 */
81
+ function buildImportRuns(config, candidates, ids, options = {}) {
82
+ const runs = { ...(config && config.runs ? config.runs : {}) };
83
+ const built = [];
84
+ for (const id of [...new Set(ids)]) {
85
+ const item = candidates.find(candidate => candidate.id === id);
86
+ if (!item) throw new Error(`本机没有可导入的 ${id}`);
87
+ if (item.invalid) throw new Error(`${agentLabelOf(item.agent)} 的本机配置不能导入:${item.invalid}`);
88
+ const provider = findProviderByBaseUrl(item.agent, item.baseUrl);
89
+ const name = uniqueRunName(runs, `${item.agent}-${provider ? provider.id : 'local'}`);
90
+ const profile = buildAgentRunProfile(item.agent, item.env);
91
+ profile.containerName = `my-${name}-{now}`;
92
+ runs[name] = profile;
93
+ built.push({ name, profile });
94
+ }
95
+ return built;
96
+ }
97
+
98
+ module.exports = { IMPORT_AGENTS, scanLocalServices, toPreview, buildImportRuns };