()
| 35 | |
| 36 | |
| 37 | def main(): |
| 38 | if not PENDING.exists(): |
| 39 | return |
| 40 | pending = rj(PENDING, []) |
| 41 | if not pending: |
| 42 | return |
| 43 | |
| 44 | cfg = rj(OPENCLAW_CFG, {}) |
| 45 | agents_list = cfg.get('agents', {}).get('list', []) |
| 46 | default_model = cfg.get('agents', {}).get('defaults', {}).get('model', {}).get('primary', '') |
| 47 | |
| 48 | applied, errors = [], [] |
| 49 | for change in pending: |
| 50 | ag_id = change.get('agentId', '').strip() |
| 51 | new_model = change.get('model', '').strip() |
| 52 | if not ag_id or not new_model: |
| 53 | errors.append({'change': change, 'error': 'missing fields'}) |
| 54 | continue |
| 55 | found = False |
| 56 | for ag in agents_list: |
| 57 | if ag.get('id') == ag_id: |
| 58 | old = ag.get('model', default_model) |
| 59 | if new_model == default_model: |
| 60 | ag.pop('model', None) |
| 61 | else: |
| 62 | ag['model'] = new_model |
| 63 | applied.append({'at': datetime.datetime.now().isoformat(), 'agentId': ag_id, 'oldModel': old, 'newModel': new_model}) |
| 64 | found = True |
| 65 | break |
| 66 | if not found: |
| 67 | errors.append({'change': change, 'error': f'agent {ag_id} not found'}) |
| 68 | |
| 69 | if applied: |
| 70 | # 只有内容真正变化时才备份和写入 |
| 71 | new_cfg = dict(cfg) |
| 72 | new_cfg['agents'] = dict(cfg.get('agents', {})) |
| 73 | new_cfg['agents']['list'] = agents_list |
| 74 | old_text = json.dumps(cfg, ensure_ascii=False, sort_keys=True) |
| 75 | new_text = json.dumps(new_cfg, ensure_ascii=False, sort_keys=True) |
| 76 | if old_text != new_text: |
| 77 | bak = OPENCLAW_CFG.parent / f'openclaw.json.bak.model-{datetime.datetime.now().strftime("%Y%m%d-%H%M%S")}' |
| 78 | shutil.copy2(OPENCLAW_CFG, bak) |
| 79 | cleanup_backups() |
| 80 | atomic_json_write(OPENCLAW_CFG, new_cfg) |
| 81 | cfg = new_cfg |
| 82 | |
| 83 | log_data = rj(CHANGE_LOG, []) |
| 84 | if not isinstance(log_data, list): |
| 85 | log_data = [] |
| 86 | log_data.extend(applied) |
| 87 | if len(log_data) > 200: |
| 88 | log_data = log_data[-200:] |
| 89 | atomic_json_write(CHANGE_LOG, log_data) |
| 90 | |
| 91 | for e in applied: |
| 92 | log.info(f'{e["agentId"]}: {e["oldModel"]} → {e["newModel"]}') |
| 93 | |
| 94 | restart_ok = False |
no test coverage detected