metame-cli 1.6.1 → 1.6.3

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.
@@ -49,7 +49,7 @@ function createBridgeStarter(deps) {
49
49
  return text || null;
50
50
  }
51
51
 
52
- async function applyUserAcl({ bot, chatId, text, config, senderId, bypassAcl }) {
52
+ async function applyUserAcl({ bot, chatId, text, config, senderId, bypassAcl, fromAllowedChat }) {
53
53
  const trimmed = String(text || '').trim();
54
54
  const normalizedSenderId = normalizeSenderId(senderId);
55
55
  if (!trimmed || bypassAcl || !userAcl) {
@@ -58,10 +58,15 @@ function createBridgeStarter(deps) {
58
58
 
59
59
  let userCtx;
60
60
  try {
61
- userCtx = userAcl.resolveUserCtx(normalizedSenderId, config || {});
61
+ userCtx = userAcl.resolveUserCtx(normalizedSenderId, config || {}, { fromAllowedChat: !!fromAllowedChat });
62
62
  } catch {
63
63
  return { blocked: false, readOnly: false, senderId: normalizedSenderId };
64
64
  }
65
+ // Audit trail for implicit-admin upgrades — these users are NOT in users.yaml
66
+ // and gain admin via group-whitelist trust, so make their action visible.
67
+ if (userCtx && userCtx.implicitAdmin) {
68
+ try { log('INFO', `[ACL] implicit admin via allowed_chat_ids: chat=${chatId} sender=${normalizedSenderId}`); } catch { /* non-fatal */ }
69
+ }
65
70
 
66
71
  const userCmd = userAcl.handleUserCommand(trimmed, userCtx);
67
72
  if (userCmd && userCmd.handled) {
@@ -736,21 +741,24 @@ function createBridgeStarter(deps) {
736
741
  const { createBot } = require('./feishu-adapter.js');
737
742
  const bot = createBot(config.feishu);
738
743
 
739
- // Validate credentials before starting WebSocket fail loud, not silent
744
+ // Credential pre-check is informational only. We always start the WS
745
+ // pipeline — it has its own network-ready-probe + backoff reconnect, so
746
+ // even if startup lands in a "just woke / network flaky" window, recovery
747
+ // is automatic instead of requiring a manual daemon restart.
740
748
  try {
741
749
  const validation = await bot.validateCredentials();
742
750
  if (!validation.ok) {
743
- log('ERROR', `Feishu credential check FAILED: ${validation.error}`);
744
751
  if (validation.isAuthError) {
745
- log('ERROR', 'Feishu bridge will NOT start fix app_id/app_secret in ~/.metame/daemon.yaml and restart daemon');
746
- return null;
752
+ log('ERROR', `Feishu credential check FAILED (likely bad app_id/app_secret): ${validation.error}`);
753
+ log('WARN', 'Starting bridge anyway — if this persists, fix ~/.metame/daemon.yaml and restart daemon');
754
+ } else {
755
+ log('WARN', `Feishu credential pre-check failed (transient): ${validation.error} — WS pipeline will retry`);
747
756
  }
748
- log('WARN', 'Feishu credential check failed (possibly network issue) — attempting to start anyway');
749
757
  } else {
750
758
  log('INFO', 'Feishu credentials validated OK');
751
759
  }
752
760
  } catch (e) {
753
- log('WARN', `Feishu credential pre-check error: ${e.message} — attempting to start anyway`);
761
+ log('WARN', `Feishu credential pre-check error: ${e.message} — WS pipeline will retry`);
754
762
  }
755
763
 
756
764
  try {
@@ -800,6 +808,7 @@ function createBridgeStarter(deps) {
800
808
  config: liveCfg,
801
809
  senderId,
802
810
  bypassAcl: !isAllowedChat && !!isBindCmd,
811
+ fromAllowedChat: isAllowedChat,
803
812
  });
804
813
  if (acl.blocked) return;
805
814
  log('INFO', `Feishu file from ${chatId}: ${fileInfo.fileName} (key: ${fileInfo.fileKey}, msgId: ${fileInfo.messageId}, type: ${fileInfo.msgType})`);
@@ -847,6 +856,7 @@ function createBridgeStarter(deps) {
847
856
  config: liveCfg,
848
857
  senderId,
849
858
  bypassAcl: !isAllowedChat && !!isBindCmd,
859
+ fromAllowedChat: isAllowedChat,
850
860
  });
851
861
  if (acl.blocked) return;
852
862
  log('INFO', `Feishu message from ${chatId}: ${text.slice(0, 50)}`);
@@ -593,7 +593,7 @@ function createCommandRouter(deps) {
593
593
  return;
594
594
  }
595
595
 
596
- if (await tryHandleAgentIntent(bot, chatId, text, config)) {
596
+ if (await tryHandleAgentIntent(bot, chatId, text, config, senderId)) {
597
597
  return;
598
598
  }
599
599
  }
@@ -15,6 +15,8 @@ const CODEX_TOOL_MAP = Object.freeze({
15
15
  web_fetch: 'WebFetch',
16
16
  });
17
17
 
18
+ const CODEX_AUTO_MODEL = 'auto';
19
+
18
20
  const ENGINE_TIMEOUT_DEFAULTS = Object.freeze({
19
21
  codex: Object.freeze({
20
22
  idleMs: 10 * 60 * 1000,
@@ -80,16 +82,19 @@ const ENGINE_MODEL_CONFIG = Object.freeze({
80
82
  hint: null,
81
83
  },
82
84
  codex: {
83
- main: 'gpt-5.4', // recommended for most tasks (official default)
85
+ main: CODEX_AUTO_MODEL, // follow official Codex CLI default model
84
86
  distill: 'gpt-5.1-codex-mini', // cost-effective mini
85
87
  options: [ // quick-pick buttons (official model names)
86
- { value: 'gpt-5.4', label: 'gpt-5.4 · 推荐' },
87
- { value: 'gpt-5.3-codex', label: 'gpt-5.3-codex · 最新 Codex 专用' },
88
+ { value: CODEX_AUTO_MODEL, label: 'auto · 跟随 Codex 官方默认' },
89
+ { value: 'gpt-5-codex', label: 'gpt-5-codex · 官方滚动别名' },
90
+ { value: 'gpt-5.5', label: 'gpt-5.5 · 固定版本' },
91
+ { value: 'gpt-5.4', label: 'gpt-5.4 · 固定版本' },
92
+ { value: 'gpt-5.3-codex', label: 'gpt-5.3-codex · 固定 Codex' },
88
93
  { value: 'gpt-5.1-codex-max', label: 'gpt-5.1-codex-max · 长任务' },
89
94
  { value: 'gpt-5.1-codex-mini', label: 'gpt-5.1-codex-mini · 轻量' },
90
95
  ],
91
96
  provider: 'openai',
92
- hint: '或直接发送任意 OpenAI 模型名切换',
97
+ hint: '推荐 `auto` 或 `gpt-5-codex`,也可直接发送任意 OpenAI 模型名切换',
93
98
  },
94
99
  });
95
100
 
@@ -121,7 +126,8 @@ function looksLikeCodexModel(model) {
121
126
  const raw = String(model || '').trim().toLowerCase();
122
127
  if (!raw) return false;
123
128
  return (
124
- raw.startsWith('gpt-')
129
+ raw === CODEX_AUTO_MODEL
130
+ || raw.startsWith('gpt-')
125
131
  || raw.startsWith('o1')
126
132
  || raw.startsWith('o3')
127
133
  || raw.startsWith('o4')
@@ -129,6 +135,10 @@ function looksLikeCodexModel(model) {
129
135
  );
130
136
  }
131
137
 
138
+ function isCodexAutoModel(model) {
139
+ return String(model || '').trim().toLowerCase() === CODEX_AUTO_MODEL;
140
+ }
141
+
132
142
  function resolveEngineModel(engineName, daemonCfg = {}, overrideModel = '') {
133
143
  const engine = normalizeEngineName(engineName);
134
144
  const engineCfg = ENGINE_MODEL_CONFIG[engine] || ENGINE_MODEL_CONFIG.claude;
@@ -393,7 +403,7 @@ function buildCodexArgs(options = {}) {
393
403
  : ['exec'];
394
404
 
395
405
  args.push('--json', '--skip-git-repo-check');
396
- if (model) args.push('-m', model);
406
+ if (model && !isCodexAutoModel(model)) args.push('-m', model);
397
407
  // -C (cwd) is only supported on fresh exec, not resume
398
408
  if (cwd && !isResume) args.push('-C', cwd);
399
409
 
@@ -178,9 +178,15 @@ const ADMIN_ONLY_ACTIONS = new Set(['system', 'agent', 'config', 'admin_acl']);
178
178
  * 根据 senderId 解析用户上下文
179
179
  * @param {string|null} senderId 飞书 open_id
180
180
  * @param {object} config daemon 配置(兼容旧 operator_ids)
181
+ * @param {object} [opts]
182
+ * @param {boolean} [opts.fromAllowedChat] 消息来自 allowed_chat_ids 命中的群。
183
+ * 当为 true 且 senderId 未在 users.yaml 显式登记时,直接判为 admin
184
+ * (群级白名单已经做过准入控制,再叠用户级 operator_ids 是冗余)。
185
+ * users.yaml 里显式登记的角色仍然受尊重。
181
186
  * @returns {object} userCtx { senderId, role, name, allowedActions, can(action) }
182
187
  */
183
- function resolveUserCtx(senderId, config) {
188
+ function resolveUserCtx(senderId, config, opts = {}) {
189
+ const fromAllowedChat = !!(opts && opts.fromAllowedChat);
184
190
  const userData = loadUsers();
185
191
  // Per-platform bootstrap: Feishu open_id starts with "ou_", Telegram IDs are numeric.
186
192
  const allUsers = userData && userData.users ? userData.users : {};
@@ -194,6 +200,7 @@ function resolveUserCtx(senderId, config) {
194
200
  const hasConfiguredUsers = hasPlatformAdmin;
195
201
 
196
202
  let role, name, allowedActions;
203
+ let implicitAdmin = false;
197
204
 
198
205
  if (!senderId) {
199
206
  // 无 ID(Telegram 等)— 兼容旧逻辑,视为 admin
@@ -215,6 +222,16 @@ function resolveUserCtx(senderId, config) {
215
222
  } else {
216
223
  allowedActions = [];
217
224
  }
225
+ } else if (fromAllowedChat) {
226
+ // Group-whitelist trust: messages reaching us through allowed_chat_ids
227
+ // already passed chat-level access control. Anyone who can speak in the
228
+ // group is treated as admin without needing operator_ids or yaml entry.
229
+ // (Explicit users.yaml entries above still win — admins can demote
230
+ // someone by writing them in.)
231
+ role = 'admin';
232
+ name = senderId.slice(-6);
233
+ allowedActions = ROLE_DEFAULT_ACTIONS.admin;
234
+ implicitAdmin = true;
218
235
  } else {
219
236
  // 兼容旧 operator_ids:若 senderId 在 operator_ids 中,视为 admin
220
237
  const operatorIds = (config && config.feishu && config.feishu.operator_ids) || [];
@@ -254,6 +271,7 @@ function resolveUserCtx(senderId, config) {
254
271
  isAdmin: role === 'admin',
255
272
  isMember: role === 'member',
256
273
  isStranger: role === 'stranger',
274
+ implicitAdmin,
257
275
  can(action) { return allowedActions.includes(action); },
258
276
  readOnly: role !== 'admin',
259
277
  };
@@ -182,6 +182,8 @@ function createWeixinBridge(deps = {}) {
182
182
  let currentAccount = null;
183
183
  let currentBot = null;
184
184
  let missingAccountLogged = false;
185
+ let pollErrorDelay = 1000; // exponential backoff on poll errors
186
+ const MAX_POLL_ERROR_DELAY = 30000;
185
187
 
186
188
  function sameAccount(a, b) {
187
189
  if (!a || !b) return false;
@@ -238,6 +240,7 @@ function createWeixinBridge(deps = {}) {
238
240
  getUpdatesBuf,
239
241
  timeoutMs: liveBridgeCfg.pollTimeoutMs,
240
242
  });
243
+ pollErrorDelay = 1000; // reset as soon as HTTP poll succeeds — downstream processMessage errors should not cause poll backoff
241
244
  if (resp && typeof resp.get_updates_buf === 'string' && resp.get_updates_buf) {
242
245
  getUpdatesBuf = resp.get_updates_buf;
243
246
  }
@@ -263,8 +266,9 @@ function createWeixinBridge(deps = {}) {
263
266
  });
264
267
  }
265
268
  } catch (err) {
266
- log('WARN', `[WEIXIN] poll error: ${err.message}`);
267
- nextDelayMs = 1000;
269
+ log('WARN', `[WEIXIN] poll error: ${err.message} — retrying in ${Math.round(pollErrorDelay / 1000)}s`);
270
+ nextDelayMs = pollErrorDelay;
271
+ pollErrorDelay = Math.min(pollErrorDelay * 2, MAX_POLL_ERROR_DELAY);
268
272
  } finally {
269
273
  processing = false;
270
274
  scheduleNext(nextDelayMs);
package/scripts/daemon.js CHANGED
@@ -106,6 +106,9 @@ const SKILL_ROUTES = [
106
106
  { name: 'heartbeat-task-manager', pattern: /提醒|remind|闹钟|定时|每[天周月]/i },
107
107
  { name: 'skill-manager', pattern: /找技能|管理技能|更新技能|安装技能|skill manager|skill scout|(?:find|look for)\s+skills?/i },
108
108
  { name: 'skill-evolution-manager', pattern: /\/evolve\b|复盘一下|记录一下(这个)?经验|保存到\s*skill|skill evolution/i },
109
+ // (?<!转) excludes "转发" forwarding semantics (e.g. "把这条消息转发给我")
110
+ // which is conversation relay, not file delivery.
111
+ { name: 'send-to-user', pattern: /(?<!转)发(?:到|给|出)?\s*(?:我|手机|飞书)|发(?:个|条|份)?\s*(?:文件|附件|图(?:片)?|日志|压缩包|截图|csv|pdf|zip|excel|表格)|(?<!转)发我|给我(?:下载|发个|发份)|send\s+(?:me|file|attachment|to\s+me)|push\s+(?:to\s+)?(?:me|phone|file)|attach\s+file/i },
109
112
  ];
110
113
 
111
114
  function routeSkill(prompt) {
@@ -1959,9 +1962,49 @@ const pendingAgentFlows = new Map();
1959
1962
  const pendingTeamFlows = new Map();
1960
1963
 
1961
1964
  // Pending activation: after creating an agent with skipChatBinding=true,
1962
- // store here so any new unbound group can activate it with /activate
1963
- // { agentKey, agentName, cwd, createdAt }
1964
- const pendingActivations = new Map(); // key: agentKey -> activation record
1965
+ // store here so any new unbound group can activate it with /activate.
1966
+ // { agentKey, agentName, cwd, createdAt, preCreatedChatId?, preCreatedChatName? }
1967
+ //
1968
+ // Persisted to disk so an auto-update / lid-close / SIGUSR2 restart in the
1969
+ // 30-minute activation window doesn't strand a freshly created Feishu chat
1970
+ // that hadn't bound yet (esp. the orphan path: createChat ok + bind fail).
1971
+ // Stale entries (>30min) are dropped on load.
1972
+ const pendingActivations = new Map();
1973
+ const PENDING_ACTIVATIONS_FILE = path.join(HOME, '.metame', 'pending_activations.json');
1974
+ const PENDING_ACTIVATIONS_TTL_MS = 30 * 60 * 1000;
1975
+ function _persistPendingActivations() {
1976
+ try {
1977
+ const obj = Object.fromEntries(pendingActivations);
1978
+ const tmp = PENDING_ACTIVATIONS_FILE + '.tmp';
1979
+ fs.writeFileSync(tmp, JSON.stringify(obj), 'utf8');
1980
+ fs.renameSync(tmp, PENDING_ACTIVATIONS_FILE);
1981
+ } catch { /* best-effort, never throw from persistence */ }
1982
+ }
1983
+ function _restorePendingActivations() {
1984
+ try {
1985
+ if (!fs.existsSync(PENDING_ACTIVATIONS_FILE)) return;
1986
+ const data = JSON.parse(fs.readFileSync(PENDING_ACTIVATIONS_FILE, 'utf8'));
1987
+ const now = Date.now();
1988
+ let restored = 0;
1989
+ for (const [k, v] of Object.entries(data)) {
1990
+ if (v && v.createdAt && now - v.createdAt < PENDING_ACTIVATIONS_TTL_MS) {
1991
+ pendingActivations.set(k, v);
1992
+ restored += 1;
1993
+ }
1994
+ }
1995
+ if (restored > 0) log('INFO', `[pending] restored ${restored} pending activation(s) from disk`);
1996
+ } catch { /* corrupt file → start fresh */ }
1997
+ }
1998
+ // Wrap Map.set/.delete so every mutation hits disk. Wrapping the prototype
1999
+ // methods (rather than reassigning) keeps the Map reference stable for callers
2000
+ // that stored it before the wrap (the daemon does not, but defensive).
2001
+ const _origPendingSet = pendingActivations.set.bind(pendingActivations);
2002
+ const _origPendingDelete = pendingActivations.delete.bind(pendingActivations);
2003
+ const _origPendingClear = pendingActivations.clear.bind(pendingActivations);
2004
+ pendingActivations.set = function (k, v) { const r = _origPendingSet(k, v); _persistPendingActivations(); return r; };
2005
+ pendingActivations.delete = function (k) { const r = _origPendingDelete(k); _persistPendingActivations(); return r; };
2006
+ pendingActivations.clear = function () { const r = _origPendingClear(); _persistPendingActivations(); return r; };
2007
+ _restorePendingActivations();
1965
2008
 
1966
2009
  const { handleAdminCommand } = createAdminCommandHandler({
1967
2010
  fs,