@xcanwin/manyoyo 8.6.12 → 8.7.1

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/bin/manyoyo.js CHANGED
@@ -61,18 +61,14 @@ const {
61
61
  formatServeLogValue,
62
62
  getServeProcessSnapshot
63
63
  } = require('../lib/serve-log');
64
+ const { formatNow, resolveQuickChatPath, expandTemplate } = require('../lib/name-template');
64
65
  const { version: BIN_VERSION, imageVersion: IMAGE_VERSION_DEFAULT } = require('../package.json');
65
66
  const IMAGE_VERSION_BASE = String(IMAGE_VERSION_DEFAULT || '1.0.0').split('-')[0];
66
67
  const IMAGE_VERSION_HELP_EXAMPLE = IMAGE_VERSION_DEFAULT || `${IMAGE_VERSION_BASE}-common`;
67
68
 
68
- // Helper function to format date like bash $(date +%m%d-%H%M)
69
+ // {now} 与默认容器名用的时间:年月日-时分秒(命令行与网页共用 lib/name-template.js)
69
70
  function formatDate() {
70
- const now = new Date();
71
- const month = String(now.getMonth() + 1).padStart(2, '0');
72
- const day = String(now.getDate()).padStart(2, '0');
73
- const hour = String(now.getHours()).padStart(2, '0');
74
- const minute = String(now.getMinutes()).padStart(2, '0');
75
- return `${month}${day}-${hour}${minute}`;
71
+ return formatNow();
76
72
  }
77
73
 
78
74
  function detectCommandName() {
@@ -95,6 +91,7 @@ const CONFIG = {
95
91
  // Default configuration
96
92
  let CONTAINER_NAME = `my-${formatDate()}`;
97
93
  let HOST_PATH = process.cwd();
94
+ let HOST_PATH_TEMPLATED = false;
98
95
  let CONTAINER_PATH = HOST_PATH;
99
96
  let IMAGE_NAME = "ghcr.io/xcanwin/manyoyo";
100
97
  let IMAGE_VERSION = IMAGE_VERSION_DEFAULT || `${IMAGE_VERSION_BASE}-common`;
@@ -159,11 +156,7 @@ function normalizeCommandSuffix(suffix) {
159
156
  }
160
157
 
161
158
  function resolveContainerNameTemplate(name) {
162
- if (typeof name !== 'string') {
163
- return name;
164
- }
165
- const nowValue = formatDate();
166
- return name.replace(/\{now\}|\$\{now\}/g, nowValue);
159
+ return expandTemplate(name, { now: formatDate() }).value;
167
160
  }
168
161
 
169
162
  function pickConfigValue(...values) {
@@ -1598,6 +1591,7 @@ https://github.com/xcanwin/manyoyo
1598
1591
  isServerStopMode,
1599
1592
  pickConfigValue,
1600
1593
  resolveContainerNameTemplate,
1594
+ templateVars: { now: formatDate(), quickChatPath: resolveQuickChatPath(config) },
1601
1595
  normalizeCommandSuffix,
1602
1596
  normalizeJsonEnvMap,
1603
1597
  normalizeCliEnvMap,
@@ -1608,6 +1602,7 @@ https://github.com/xcanwin/manyoyo
1608
1602
  });
1609
1603
 
1610
1604
  HOST_PATH = resolvedRuntime.hostPath;
1605
+ HOST_PATH_TEMPLATED = resolvedRuntime.hostPathTemplated === true;
1611
1606
  CONTAINER_NAME = resolvedRuntime.containerName;
1612
1607
  CONTAINER_PATH = resolvedRuntime.containerPath;
1613
1608
  IMAGE_NAME = resolvedRuntime.imageName;
@@ -1827,6 +1822,7 @@ function createRuntimeContext(modeState = {}) {
1827
1822
  return {
1828
1823
  containerName: CONTAINER_NAME,
1829
1824
  hostPath: HOST_PATH,
1825
+ hostPathTemplated: HOST_PATH_TEMPLATED,
1830
1826
  containerPath: CONTAINER_PATH,
1831
1827
  imageName: IMAGE_NAME,
1832
1828
  imageVersion: IMAGE_VERSION,
@@ -1877,6 +1873,10 @@ function handleRemoveContainer(runtime) {
1877
1873
  }
1878
1874
 
1879
1875
  function validateHostPath(runtime) {
1876
+ // 目录是按模板({now} / {quickChatPath})生成的:此刻才建,只在真的要用它的时候建
1877
+ if (runtime.hostPathTemplated && !fs.existsSync(runtime.hostPath)) {
1878
+ fs.mkdirSync(runtime.hostPath, { recursive: true });
1879
+ }
1880
1880
  if (!fs.existsSync(runtime.hostPath)) {
1881
1881
  console.log(`${RED}⚠️ 错误: 宿主机路径不存在: ${runtime.hostPath}${NC}`);
1882
1882
  process.exit(1);
@@ -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
  };
@@ -701,5 +701,6 @@ module.exports = {
701
701
  parseHostsAndResolv,
702
702
  parseUrlHostPort,
703
703
  isHostTarget,
704
+ isMissingImageError,
704
705
  createNetworkManager
705
706
  };
@@ -25,7 +25,8 @@ const AGENT_ENV_SCHEMA = {
25
25
  { name: 'ANTHROPIC_DEFAULT_OPUS_MODEL', description: 'Opus 档位对应的模型', secret: false },
26
26
  { name: 'ANTHROPIC_DEFAULT_SONNET_MODEL', description: 'Sonnet 档位对应的模型', secret: false },
27
27
  { name: 'ANTHROPIC_DEFAULT_HAIKU_MODEL', description: 'Haiku 档位对应的模型', secret: false },
28
- { name: 'CLAUDE_CODE_SUBAGENT_MODEL', description: '子 Agent 使用的模型', secret: false }
28
+ { name: 'CLAUDE_CODE_SUBAGENT_MODEL', description: '子 Agent 使用的模型', secret: false },
29
+ { name: 'ENABLE_TOOL_SEARCH', description: '工具搜索(部分兼容服务要设为 false,否则模型调不了工具)', secret: false }
29
30
  ]
30
31
  },
31
32
  codex: {
@@ -481,6 +482,8 @@ async function initAgentConfigs(rawAgents, options = {}) {
481
482
 
482
483
  module.exports = {
483
484
  initAgentConfigs,
485
+ collectClaudeInitData,
486
+ collectCodexInitData,
484
487
  AGENT_ENV_SCHEMA,
485
488
  agentEnvKeys
486
489
  };
@@ -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 };