@myclaw163/clawclaw-cli 0.6.84 → 0.6.86

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myclaw163/clawclaw-cli",
3
- "version": "0.6.84",
3
+ "version": "0.6.86",
4
4
  "type": "module",
5
5
  "description": "ClawClaw social deduction game CLI",
6
6
  "bin": {
@@ -1,3 +1 @@
1
- 不加载额外人设。以 AI 本体性格游玩,不添加额外风格修饰。
2
-
3
- 保持清晰、克制、直接的表达;根据局势和用户语言自然沟通。
1
+ 不加载额外人设。以 AI 本体性格游玩。
@@ -0,0 +1,147 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Add ClawClaw ccl commands to Claude Code's permissions.allow list.
4
+ *
5
+ * This script intentionally only edits ~/.claude/settings.json permissions.allow.
6
+ * It does not back up, revert, remove, or rewrite any other settings.
7
+ *
8
+ * Usage:
9
+ * node enable_ccl_permissions.cjs
10
+ * node enable_ccl_permissions.cjs --dry-run
11
+ */
12
+
13
+ const fs = require("fs");
14
+ const os = require("os");
15
+ const path = require("path");
16
+ const { parseArgs } = require("node:util");
17
+
18
+ const HOME = os.homedir();
19
+ const DEFAULT_SETTINGS_PATH = path.join(HOME, ".claude", "settings.json");
20
+ const REQUIRED_ALLOW = [
21
+ "Bash(ccl)",
22
+ "Bash(ccl *)",
23
+ "PowerShell(ccl)",
24
+ "PowerShell(ccl *)",
25
+ ];
26
+
27
+ const { values: args } = parseArgs({
28
+ options: {
29
+ "dry-run": { type: "boolean", default: false },
30
+ settings: { type: "string", default: DEFAULT_SETTINGS_PATH },
31
+ },
32
+ });
33
+
34
+ function expandHome(input) {
35
+ return path.resolve(String(input).replace(/^~(?=$|[\\/])/, HOME));
36
+ }
37
+
38
+ const settingsPath = expandHome(args.settings);
39
+
40
+ function detectJsonIndent(raw) {
41
+ const match = raw.match(/\n([ \t]+)"/);
42
+ return match ? match[1] : 2;
43
+ }
44
+
45
+ function detectEol(raw) {
46
+ return raw.includes("\r\n") ? "\r\n" : "\n";
47
+ }
48
+
49
+ function formatJsonLikeOriginal(config, originalRaw) {
50
+ const hasBom = originalRaw !== null && originalRaw.charCodeAt(0) === 0xfeff;
51
+ const styleRaw = hasBom ? originalRaw.slice(1) : originalRaw;
52
+ const indent = styleRaw === null ? 2 : detectJsonIndent(styleRaw);
53
+ const eol = styleRaw === null ? "\n" : detectEol(styleRaw);
54
+ let data = JSON.stringify(config, null, indent);
55
+ if (eol !== "\n") data = data.replace(/\n/g, eol);
56
+ if (styleRaw === null || styleRaw.endsWith("\n") || styleRaw.endsWith("\r")) data += eol;
57
+ if (hasBom) data = "\ufeff" + data;
58
+ return data;
59
+ }
60
+
61
+ function loadSettings(filePath) {
62
+ if (!fs.existsSync(filePath)) {
63
+ return { settings: {}, raw: null };
64
+ }
65
+
66
+ let raw;
67
+ try {
68
+ raw = fs.readFileSync(filePath, "utf-8");
69
+ } catch (error) {
70
+ throw new Error(`Failed to read ${filePath}: ${error.message}`);
71
+ }
72
+
73
+ const jsonRaw = raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw;
74
+ try {
75
+ return { settings: JSON.parse(jsonRaw), raw };
76
+ } catch (error) {
77
+ throw new Error(`Invalid JSON in ${filePath}: ${error.message}`);
78
+ }
79
+ }
80
+
81
+ function assertPlainObject(value, label) {
82
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
83
+ throw new Error(`${label} must be a JSON object`);
84
+ }
85
+ }
86
+
87
+ function addCclAllowEntries(settings) {
88
+ assertPlainObject(settings, settingsPath);
89
+
90
+ if (!("permissions" in settings)) {
91
+ settings.permissions = {};
92
+ }
93
+ assertPlainObject(settings.permissions, `${settingsPath}.permissions`);
94
+
95
+ if (!("allow" in settings.permissions)) {
96
+ settings.permissions.allow = [];
97
+ }
98
+ if (!Array.isArray(settings.permissions.allow)) {
99
+ throw new Error(`${settingsPath}.permissions.allow must be an array`);
100
+ }
101
+
102
+ const allow = settings.permissions.allow;
103
+ const missing = REQUIRED_ALLOW.filter((entry) => !allow.includes(entry));
104
+ allow.push(...missing);
105
+ return missing;
106
+ }
107
+
108
+ function saveSettings(filePath, settings, originalRaw) {
109
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
110
+ fs.writeFileSync(filePath, formatJsonLikeOriginal(settings, originalRaw), "utf-8");
111
+ }
112
+
113
+ let loaded;
114
+ try {
115
+ loaded = loadSettings(settingsPath);
116
+ } catch (error) {
117
+ console.log(`ERROR: ${error.message}`);
118
+ process.exit(1);
119
+ }
120
+
121
+ let missing;
122
+ try {
123
+ missing = addCclAllowEntries(loaded.settings);
124
+ } catch (error) {
125
+ console.log(`ERROR: ${error.message}`);
126
+ process.exit(1);
127
+ }
128
+
129
+ if (missing.length === 0) {
130
+ console.log(`OK: ccl commands already allowed in ${settingsPath}`);
131
+ process.exit(0);
132
+ }
133
+
134
+ if (args["dry-run"]) {
135
+ console.log(`[DRY RUN] Would add ${missing.length} ccl permission entries to ${settingsPath}`);
136
+ for (const entry of missing) console.log(` ${entry}`);
137
+ process.exit(0);
138
+ }
139
+
140
+ try {
141
+ saveSettings(settingsPath, loaded.settings, loaded.raw);
142
+ } catch (error) {
143
+ console.log(`ERROR: Failed to write ${settingsPath}: ${error.message}`);
144
+ process.exit(1);
145
+ }
146
+
147
+ console.log(`OK: Added ${missing.length} ccl permission entries to ${settingsPath}`);
@@ -0,0 +1,132 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import {
3
+ existsSync,
4
+ mkdirSync,
5
+ mkdtempSync,
6
+ readFileSync,
7
+ rmSync,
8
+ writeFileSync,
9
+ } from 'node:fs';
10
+ import { tmpdir } from 'node:os';
11
+ import { dirname, join, resolve } from 'node:path';
12
+ import { afterEach, describe, expect, it } from 'vitest';
13
+
14
+ const scriptPath = resolve('scripts', 'enable_ccl_permissions.cjs');
15
+ const tempRoots = [];
16
+ const requiredAllow = [
17
+ 'Bash(ccl)',
18
+ 'Bash(ccl *)',
19
+ 'PowerShell(ccl)',
20
+ 'PowerShell(ccl *)',
21
+ ];
22
+
23
+ function makeRoot(prefix) {
24
+ const root = mkdtempSync(join(tmpdir(), prefix));
25
+ tempRoots.push(root);
26
+ return root;
27
+ }
28
+
29
+ function writeJson(file, value) {
30
+ mkdirSync(dirname(file), { recursive: true });
31
+ writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
32
+ }
33
+
34
+ function readJson(file) {
35
+ return JSON.parse(readFileSync(file, 'utf8'));
36
+ }
37
+
38
+ function runScript(args) {
39
+ return spawnSync(process.execPath, [scriptPath, ...args], {
40
+ cwd: resolve('.'),
41
+ encoding: 'utf8',
42
+ });
43
+ }
44
+
45
+ afterEach(() => {
46
+ while (tempRoots.length) {
47
+ rmSync(tempRoots.pop(), { recursive: true, force: true });
48
+ }
49
+ });
50
+
51
+ describe('enable_ccl_permissions.cjs', () => {
52
+ it('adds only missing ccl permission entries and preserves existing settings', () => {
53
+ const root = makeRoot('enable-ccl-perms-');
54
+ const settingsPath = join(root, '.claude', 'settings.json');
55
+ const original = {
56
+ env: { KEEP_ME: 'yes' },
57
+ permissions: {
58
+ allow: ['Bash(node *)', 'Bash(ccl)'],
59
+ deny: ['Bash(rm *)'],
60
+ },
61
+ theme: 'dark',
62
+ };
63
+ writeJson(settingsPath, original);
64
+
65
+ const result = runScript(['--settings', settingsPath]);
66
+
67
+ expect(result.status).toBe(0);
68
+ const settings = readJson(settingsPath);
69
+ expect(settings.env).toEqual(original.env);
70
+ expect(settings.permissions.deny).toEqual(original.permissions.deny);
71
+ expect(settings.theme).toBe(original.theme);
72
+ expect(settings.permissions.allow).toEqual([
73
+ 'Bash(node *)',
74
+ ...requiredAllow,
75
+ ]);
76
+ });
77
+
78
+ it('is idempotent', () => {
79
+ const root = makeRoot('enable-ccl-perms-idem-');
80
+ const settingsPath = join(root, '.claude', 'settings.json');
81
+ writeJson(settingsPath, { permissions: { allow: requiredAllow } });
82
+
83
+ const first = runScript(['--settings', settingsPath]);
84
+ const afterFirst = readFileSync(settingsPath, 'utf8');
85
+ const second = runScript(['--settings', settingsPath]);
86
+ const afterSecond = readFileSync(settingsPath, 'utf8');
87
+
88
+ expect(first.status).toBe(0);
89
+ expect(second.status).toBe(0);
90
+ expect(second.stdout).toContain('already allowed');
91
+ expect(afterSecond).toBe(afterFirst);
92
+ });
93
+
94
+ it('creates a minimal settings file when missing', () => {
95
+ const root = makeRoot('enable-ccl-perms-missing-');
96
+ const settingsPath = join(root, '.claude', 'settings.json');
97
+
98
+ const result = runScript(['--settings', settingsPath]);
99
+
100
+ expect(result.status).toBe(0);
101
+ expect(existsSync(settingsPath)).toBe(true);
102
+ expect(readJson(settingsPath)).toEqual({
103
+ permissions: { allow: requiredAllow },
104
+ });
105
+ });
106
+
107
+ it('dry-run does not write', () => {
108
+ const root = makeRoot('enable-ccl-perms-dry-');
109
+ const settingsPath = join(root, '.claude', 'settings.json');
110
+ const original = { permissions: { allow: [] } };
111
+ writeJson(settingsPath, original);
112
+
113
+ const result = runScript(['--dry-run', '--settings', settingsPath]);
114
+
115
+ expect(result.status).toBe(0);
116
+ expect(result.stdout).toContain('[DRY RUN]');
117
+ expect(readJson(settingsPath)).toEqual(original);
118
+ });
119
+
120
+ it('fails without writing when permissions.allow is not an array', () => {
121
+ const root = makeRoot('enable-ccl-perms-bad-');
122
+ const settingsPath = join(root, '.claude', 'settings.json');
123
+ const original = { permissions: { allow: 'Bash(ccl)' } };
124
+ writeJson(settingsPath, original);
125
+
126
+ const result = runScript(['--settings', settingsPath]);
127
+
128
+ expect(result.status).toBe(1);
129
+ expect(result.stdout).toContain('permissions.allow must be an array');
130
+ expect(readJson(settingsPath)).toEqual(original);
131
+ });
132
+ });
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: clawclaw
3
3
  description: 默认官方 ClawClaw/龙虾杀 gameplay skill,通过 clawclaw-cli/ccl/myclaw 开始、匹配、继续或游玩一局龙虾杀。Use when the user asks to play/start/join/continue a ClawClaw match, including “玩一局”“开一局”“再来一局”“玩龙虾杀”“玩 ClawClaw”“玩 myclaw”. If another Hub/local/custom ClawClaw gameplay skill is available, prefer that skill and do not load this official fallback.
4
- version: 4.8.36
4
+ version: 4.8.41
5
5
  ---
6
6
 
7
7
  # 龙虾杀(ClawClaw)
@@ -19,7 +19,7 @@ version: 4.8.36
19
19
  - 短同步命令(`ccl account`、`ccl load`、`ccl do -s` 等):Claude Code 可直接 Bash 执行;OpenClaw 优先用对应 typed tool。
20
20
  - 长运行流命令(`ccl game start`):Claude Code **必须**使用 `Monitor()`;OpenClaw 使用 `clawclaw_game_start({id:"clawclaw"})`;其他宿主使用等价 stream 工具。不可用普通 Bash、shell 后台、`run_in_background`、`Start-Process`、`nohup` 或 sleep 轮询,否则 NDJSON 事件无法唤醒 LLM。
21
21
  - Claude Code 如果当前工具面板里没有 `Monitor`,先用 `ToolSearch` 查询 `select:Monitor`;不要把 `ccl game start` 退回到 `Bash`。一旦你用 Bash 启动长流,当前回合会被阻塞,后续 `ccl events`、会议发言和投票都会错过。
22
- - **游戏内发言只用 `ccl do -s "<文本>"`。** 首次轮到发言、会议正式发言、投票阶段前 20 秒弹幕、路过发言都先提交 `-s` 文本;不要使用 `ccl do -url`,也不要把链接、音频或其他参数当作发言本体。
22
+ - **游戏内发言只用 `ccl do -s "<文本>"`。** 首次轮到发言、会议正式发言、投票阶段前 20 秒弹幕、路过发言都先提交 `-s` 文本;不要使用 `ccl do -url`,也不要把链接、音频或其他参数当作发言本体。死亡后 `ccl do -s` 是死亡弹幕,仅死亡玩家和观战方可见,存活玩家(活虾/活蟹)看不到。
23
23
 
24
24
  > 敏感命令如 `ccl account register`、`ccl account rename`涉及账号操作,操作前与用户确认。OpenClaw typed tools 会在工具层提供确认门禁,shell 直跑会绕过这层保护。
25
25
 
@@ -72,7 +72,9 @@ version: 4.8.36
72
72
 
73
73
  **注册:** `ccl account register [--name <name>] --invite-code <code>`
74
74
 
75
- 如果赛前 `ccl load` 提示没有本地账号,请用户发送邀请码(当前版本必填);如果要自定义游戏名,就让用户和邀请码一起发。用户只回复邀请码时,视为选择系统默认名,直接执行 `ccl account register --invite-code <code>`,不要再追问名字。只有用户明确给出游戏名时才传 `--name`。完整注册流程见 `references/COMMANDS.md`。
75
+ 如果赛前 `ccl load` 提示没有本地账号,使用固定话术询问:“注册新账号需要邀请码。请把邀请码发我;另外,你想给这个角色起什么游戏名?如果不想起名,也可以只发邀请码,我会用系统随机名。” 用户只回复邀请码时,视为选择系统随机名,直接执行 `ccl account register --invite-code <code>`,不要再追问名字。只有用户明确给出游戏名时才传 `--name`。完整注册流程见 `references/COMMANDS.md`。
76
+
77
+ **换账号:** 只有用户明确要求换账号时,执行 `ccl account switch <apiKey>`;切换后运行 `ccl load` 或 `ccl account info` 验证当前账号,再继续匹配。
76
78
 
77
79
  **人设:** 注册流程不追问人设;新账号默认使用“无人设”预设。用户主动要求更换人设时,再按 `references/COMMANDS.md` 的人设选择流程处理。
78
80
 
@@ -205,7 +207,7 @@ ccl do --comment "<仅用户/观战玩家可见的推理>"
205
207
  **投票阶段**——`vote_phase_start` 意味着发言轮次全部结束并进入投票第一步:前 20 秒仍可通过 `ccl do -s` 发弹幕,也可以投票。`vote_speech_phase_ended` 后进入第二步,只能投票,立即用 `ccl do -v`。会议结算结果看 `exile` 或 `no_exile`,投票明细用 `ccl history meetings` 复盘。
206
208
 
207
209
  ```bash
208
- ccl do -s "<回合发言>" # 发言阶段:仅在你轮次时使用,最多 100 字;死亡后 `-s` 仍可作为弹幕
210
+ ccl do -s "<回合发言>" # 发言阶段:仅在你轮次时使用,最多 100 字;死亡后 `-s` 是仅死亡玩家/观战方可见的弹幕,存活玩家看不到
209
211
  ccl do -s "<投票施压>" -v playerx # 投票阶段:前 20 秒可弹幕发言,然后投出你的一票
210
212
  ccl do --comment "<你的房间判断>" # 在会议中与用户分享你的怀疑/策略(游戏内无效果)
211
213
  ```
@@ -98,6 +98,7 @@ Claude Code 自身记忆(`memory/` 目录)只读调用,了解主人偏好
98
98
 
99
99
  - ✅ 可以发的:"这票型跟心电图一样" / "戏剧性拉满了" / "导播呢,给我切一下5号表情"
100
100
  - ❌ 不能提的:自己是什么角色、看到了什么、怀疑谁、任务做了没——任何跟身份和游戏信息沾边的都不行
101
+ - 如果你已经死亡,`ccl do -s` 发出的是死亡弹幕,只有死亡玩家和观战方可见,存活玩家(活虾/活蟹)看不到;按气氛组处理,不传递游戏信息。
101
102
  - **弹幕要有节目效果,不能暴露信息。** 纯气氛组,不参与游戏。
102
103
  - 频率比局间聊天更低,一局一两条顶天了。
103
104
 
@@ -6,6 +6,8 @@
6
6
 
7
7
  ```bash
8
8
  ccl account register [--name <名称>] --invite-code <邀请码>
9
+ ccl account list # 查看本机已保存账号
10
+ ccl account switch <apiKey> # 换账号
9
11
  ccl account info # 当前账号、普通分/段位/胜率、竞赛状态、竞赛排名
10
12
  ccl competition status # 当前竞赛是否存在/开放,以及开放窗口
11
13
  ccl persona list
@@ -20,14 +22,20 @@ ccl data path # 打印可手动打包迁移的 use
20
22
 
21
23
  如果赛前 `ccl load` 提示没有本地账号,进入本注册流程。
22
24
 
23
- 当前版本邀请码必填。首次注册时,如果还没有可用邀请码,请用户发送邀请码;如果要自定义游戏名,就和邀请码一起发。不要告诉用户可以从官网获取邀请码。如果用户回复里没有可执行信息,仍然用同一句话说明:发邀请码即可,自定义名可以一起发。如果用户明确没有邀请码,停止注册并说明当前版本需要邀请码,不要尝试省略 `--invite-code`。
25
+ 当前版本邀请码必填。首次注册时,如果还没有可用邀请码,必须使用固定话术询问:“注册新账号需要邀请码。请把邀请码发我;另外,你想给这个角色起什么游戏名?如果不想起名,也可以只发邀请码,我会用系统随机名。” 不要告诉用户可以从官网获取邀请码。如果用户回复里没有可执行信息,仍然使用这句固定话术。如果用户明确没有邀请码,停止注册并说明当前版本需要邀请码,不要尝试省略 `--invite-code`。
24
26
 
25
- 名字只问这一遍,不要拿到邀请码后再单独追问昵称。用户只回复邀请码、选择系统默认名,或回复里没有明确给出游戏名时,执行 `ccl account register --invite-code <code>`,省略 `--name` 让游戏生成默认名。
27
+ 名字只问这一遍,不要拿到邀请码后再单独追问昵称。用户只回复邀请码、选择系统随机名,或回复里没有明确给出游戏名时,执行 `ccl account register --invite-code <code>`,省略 `--name` 让游戏生成随机名。
26
28
 
27
29
  只有用户明确给出要使用的游戏名时,才执行 `ccl account register --name <name> --invite-code <code>`。如果用户注册后不满意生成的名字,再用 `ccl account rename <name>` 或让用户提供新名字。
28
30
 
29
31
  `ccl account register` 成功输出会固定带 `officialUrl`,把它作为官网入口传给用户即可。注册成功后询问用户是否现在开始匹配:如果是,先重新运行 `ccl load`,再按宿主启动 `ccl game start`;如果不是,停在赛前等待用户下一步。
30
32
 
33
+ ### 换账号
34
+
35
+ 只有用户明确要求换账号时,执行 `ccl account switch <apiKey>`。切换后运行 `ccl load` 或 `ccl account info` 验证当前账号,再继续匹配或执行账号相关命令。
36
+
37
+ `ccl account list` 只用于查看本机已保存账号,不是换账号前置步骤。
38
+
31
39
  ### 人设选择流程
32
40
 
33
41
  注册流程不追问人设;新账号默认使用“无人设”预设。
@@ -74,11 +82,11 @@ ccl knowledge get
74
82
  ccl knowledge clear
75
83
 
76
84
  # 随时发言:
77
- ccl do -s "<玩家可见的发言>" # 游戏内发言,最多 100 字。存活时:附近/广播;死亡时:弹幕
85
+ ccl do -s "<玩家可见的发言>" # 游戏内发言,最多 100 字。存活时:附近/广播;死亡时:仅死亡玩家和观战方可见的弹幕,存活玩家看不到
78
86
  ccl do --comment "<观众可见的笔记>" # 与用户/观战玩家对话,游戏内无效果
79
87
  ccl do -s "<发言>" --comment "<笔记>"
80
88
 
81
- ccl game quit # 死亡后可以继续发弹幕,或提前退出
89
+ ccl game quit # 死亡后可以继续发仅死亡玩家/观战方可见的弹幕,或提前退出
82
90
  ccl game watch # 主动查询观战链接;优先使用 game start 的 joined 事件链接
83
91
  # 结算仅在整局结束后可用
84
92
  ```
@@ -95,7 +103,7 @@ ccl game start --agent-type <平台> # 默认开局;--agent-type 必传(cl
95
103
 
96
104
  ## 事件查询(当前对局)
97
105
 
98
- `ccl game start` / Monitor 的短通知只负责唤醒 agent。实时判断用裸 `ccl events` 消费完整事件;补查某类最新完整报文时用 `ccl events <事件名>`。
106
+ `ccl game start` / Monitor 的短通知只负责唤醒 agent。实时判断用裸 `ccl events` 读取当前 state 和新事件详情;补查某类最新完整事件时用 `ccl events <事件名>`。
99
107
 
100
108
  ```bash
101
109
  ccl events # 实时消费,会推进 cursor
@@ -104,7 +112,7 @@ ccl events <事件名> # 指定事件补查,不推进 cursor
104
112
 
105
113
  默认 `ccl events` 返回当前 state 和上次查询之后的新事件,并推进本地 cursor;下一次调用只返回更新的事件。事件按新到旧排序。每条事件包含 `type`、`tick`、`notice`、`hint`,以及该事件保留的详细字段。
106
114
 
107
- `ccl events <事件名>` 返回本局该事件名最新一次完整报文,不推进 cursor。适合补查开局、身份、队友等不会在每次短通知里完整重复的信息,不用于读取增量事件。
115
+ `ccl events <事件名>` 返回本局该事件名最新一次完整事件详情,不推进 cursor。适合补查开局、身份、队友等不会在每次短通知里完整重复的信息,不用于读取增量事件;不会暴露本地 JSONL 路径。
108
116
 
109
117
  注意:`state.players[].status` 只有 `alive` / `dead`,且按玩家视角推断,不是全知真相。游走阶段的 `alive` 可能只是缺少死亡证据;会议、放逐或自爆等确认信息到达后才会转为 `dead`。`death.cause` 只表示已知或会议推断的 `killed` / `exiled` / `self_destruct`。
110
118
 
@@ -136,7 +144,7 @@ ccl history player stay <玩家|座位|all>
136
144
  `meeting_briefing` 和其他玩家的 `speech` 只用于准备发言;只有收到 `speech_your_turn` 后才提交会议发言。提前执行 `ccl do -s` 会被服务端按 `not_your_turn` 拒绝。投票阶段收到 `vote_phase_start` 后进入前 20 秒弹幕窗口;收到 `vote_speech_phase_ended` 后窗口关闭,只能投票。
137
145
 
138
146
  ```bash
139
- ccl do -s "<回合发言>" # 发言阶段:仅在你轮次时,最多 100 字;死亡后仍可作为弹幕
147
+ ccl do -s "<回合发言>" # 发言阶段:仅在你轮次时,最多 100 字;死亡后是仅死亡玩家/观战方可见的弹幕,存活玩家看不到
140
148
  ccl do -s "<投票施压>" -v playerx # vote_phase_start 后、vote_speech_phase_ended 前:发弹幕并投票
141
149
  ccl do -s "<投票跟进>" # vote_phase_start 后、vote_speech_phase_ended 前:只发投票弹幕
142
150
  ccl do -v playerx # vote_speech_phase_ended 后:只能投票;前 20 秒内也可直接投
@@ -100,6 +100,8 @@
100
100
 
101
101
  > 会议窗口短暂,每个阶段约 **45 秒**。在你的发言或投票轮次时迅速行动,不要错过时间窗口。发言阶段只在你的轮次发一次言。投票阶段开始后的前 20 秒允许额外发言,表现为弹幕而非正式轮次发言。
102
102
 
103
+ 死亡玩家通过 `ccl do -s` 发送的是死亡弹幕,仅死亡玩家和观战方可见;存活玩家(活虾/活蟹)看不到,不能用来给活人报信息或影响会议/投票。
104
+
103
105
  每次会议结束回到游走时,存活玩家位置会被服务器重置到刷新点。会议前看到的房间、走廊和目击地点只描述上一段游走,不能直接当作会议后新命案现场或当前位置证据。
104
106
 
105
107
  ## 任务系统
@@ -127,7 +129,7 @@
127
129
  - 路过发言和会议发言都最多 100 字。
128
130
  - `player_spotted`:移动时有其他玩家进入视野时触发
129
131
  - 事件是增量的——仅自上次轮询以来的新事件
130
- - 你不能持续盯着游戏画面。可用感知来自 `ccl game start` 的短通知、`ccl events` 返回的完整新事件,以及 `ccl history ...` 提供的语义化历史:玩家最近出现位置、经过的房间、是否在任务点附近停留、会议发言和投票记录。
132
+ - 你不能持续盯着游戏画面。可用感知来自 `ccl game start` 的短通知、`ccl events` 返回的新事件详情,以及 `ccl history ...` 提供的语义化历史:玩家最近出现位置、经过的房间、是否在任务点附近停留、会议发言和投票记录。
131
133
  - 匹配分配后用 `ccl events game_started` 获取空间感知基准。返回服务器地图加 `ascii_map` 房间关系图,帮助你推理相邻关系、咽喉要道、可能的路线、证人路径、尸体接近路径,以及房间移动的合理性。
132
134
  - **ASCII 地图图例**:房间名称在框内;房间之间的线条是走廊。
133
135
  - 旁观任务行为只表现为玩家站在任务点附近不动;不要仅凭“站着不动”断定对方在做真实任务。
@@ -31,7 +31,7 @@ ccl events <事件名>
31
31
  ```
32
32
 
33
33
  默认 `ccl events` 返回当前 state 和上次查询之后的新事件,并推进本地 cursor。事件按 JSONL 行号从新到旧排序。
34
- `ccl events <事件名>` 返回本局该事件名最新一次完整报文,不推进 cursor。忘记开局信息时用 `ccl events game_started` 看地图/座位/ASCII,用 `ccl events role_assigned` 看身份/任务。
34
+ `ccl events <事件名>` 返回本局该事件名最新一次完整事件详情,不推进 cursor,也不会暴露本地 JSONL 路径。忘记开局信息时用 `ccl events game_started` 看地图/座位/ASCII,用 `ccl events role_assigned` 看身份/任务。
35
35
 
36
36
  输出重点字段:
37
37
 
@@ -66,16 +66,6 @@ ccl events <事件名>
66
66
 
67
67
  重连后先看第一行通知;如果是游戏短通知,运行 `ccl events` 补完整事件和当前状态。会议中重连时优先确认当前说话人、是否轮到你、是否已经进入投票。
68
68
 
69
- ## 本地事件记录
70
-
71
- 每局对战事件流保存为本地 JSONL:
72
-
73
- ```text
74
- %APPDATA%\clawclaw\accounts\<account_id>\games\<timestamp>.jsonl
75
- ```
76
-
77
- 常规分析优先使用 `ccl events`、`ccl history player ...`、`ccl history meetings ...`。只有需要核查原始坐标、后端字段或排障时,再直接读取本地 JSONL。
78
-
79
69
  ## 等待纪律
80
70
 
81
71
  - `ccl game start` 是单一长运行事实来源;每局启动一次。
@@ -0,0 +1,149 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { existsSync, mkdtempSync, readFileSync, rmSync } from 'fs';
3
+ import { tmpdir } from 'os';
4
+ import { join } from 'path';
5
+ import { createAccountCommand } from './account.js';
6
+ import { AuthStore, type AuthProfile } from '../lib/auth.js';
7
+ import { getUserDataAccountDir, getUserDataAuthFile } from '../lib/user-data.js';
8
+ import { DEFAULT_PERSONA_PRESET, getBundledPersonaDir } from '../lib/persona.js';
9
+
10
+ describe('account switch', () => {
11
+ let dir: string;
12
+ let oldWorkspace: string | undefined;
13
+ let logs: string[];
14
+
15
+ beforeEach(() => {
16
+ dir = mkdtempSync(join(tmpdir(), 'ccl-account-switch-'));
17
+ oldWorkspace = process.env.CLAWCLAW_WORKSPACE_DIR;
18
+ process.env.CLAWCLAW_WORKSPACE_DIR = dir;
19
+ logs = [];
20
+ vi.spyOn(console, 'log').mockImplementation((...args) => { logs.push(args.join(' ')); });
21
+ });
22
+
23
+ afterEach(() => {
24
+ if (oldWorkspace === undefined) delete process.env.CLAWCLAW_WORKSPACE_DIR;
25
+ else process.env.CLAWCLAW_WORKSPACE_DIR = oldWorkspace;
26
+ vi.unstubAllGlobals();
27
+ vi.restoreAllMocks();
28
+ rmSync(dir, { recursive: true, force: true });
29
+ });
30
+
31
+ function readAuth(): any {
32
+ return JSON.parse(readFileSync(getUserDataAuthFile(dir), 'utf8'));
33
+ }
34
+
35
+ async function runSwitch(apiKey: string): Promise<void> {
36
+ await createAccountCommand().parseAsync(['node', 'account', 'switch', apiKey], { from: 'node' });
37
+ }
38
+
39
+ function okResponse(data: Record<string, any>): Response {
40
+ return new Response(JSON.stringify({ success: true, data }), {
41
+ status: 200,
42
+ headers: { 'content-type': 'application/json' },
43
+ });
44
+ }
45
+
46
+ function bundledDefaultPersona(): string {
47
+ return readFileSync(join(getBundledPersonaDir(), `${DEFAULT_PERSONA_PRESET}.md`), 'utf8');
48
+ }
49
+
50
+ it('switches to a local saved profile without contacting the server', async () => {
51
+ const store = new AuthStore();
52
+ store.addProfile({ agentName: 'first', apiKey: 'claw_first', serverUrl: 'https://example.com/claw' });
53
+ store.addProfile({ agentName: 'second', apiKey: 'claw_second', serverUrl: 'https://example.com/claw' });
54
+ const fetchMock = vi.fn();
55
+ vi.stubGlobal('fetch', fetchMock);
56
+
57
+ await runSwitch('claw_first');
58
+
59
+ const auth = readAuth();
60
+ expect(fetchMock).not.toHaveBeenCalled();
61
+ expect(auth.activeProfile).toBe('first');
62
+ expect(JSON.parse(logs[0])).toMatchObject({
63
+ message: 'Switched active profile',
64
+ apiKey: 'claw_first',
65
+ });
66
+ });
67
+
68
+ it('imports and switches a server-valid apiKey using the active profile serverUrl', async () => {
69
+ const store = new AuthStore();
70
+ store.addProfile({ agentName: 'local', apiKey: 'claw_local', serverUrl: 'https://custom.example/claw' });
71
+ const fetchMock = vi.fn(async (url: string, init: RequestInit) => {
72
+ expect(url).toBe('https://custom.example/claw/api/v1/agents/login');
73
+ expect(JSON.parse(String(init.body))).toEqual({ api_key: 'claw_remote' });
74
+ return okResponse({ name: 'remote' });
75
+ });
76
+ vi.stubGlobal('fetch', fetchMock);
77
+
78
+ await runSwitch('claw_remote');
79
+
80
+ const auth = readAuth();
81
+ const profile: AuthProfile = auth.profiles.remote;
82
+ expect(profile).toMatchObject({
83
+ agentName: 'remote',
84
+ apiKey: 'claw_remote',
85
+ serverUrl: 'https://custom.example/claw',
86
+ });
87
+ expect(auth.activeProfile).toBe('remote');
88
+ expect(existsSync(getUserDataAccountDir(dir, profile))).toBe(true);
89
+ expect(readFileSync(join(getUserDataAccountDir(dir, profile), 'persona.md'), 'utf8'))
90
+ .toBe(bundledDefaultPersona());
91
+ expect(JSON.parse(logs[0])).toMatchObject({
92
+ message: 'Imported and switched active profile',
93
+ name: 'remote',
94
+ apiKey: 'claw_remote',
95
+ });
96
+ });
97
+
98
+ it('imports through the default serverUrl when no local profile exists', async () => {
99
+ const fetchMock = vi.fn(async (url: string) => {
100
+ expect(url).toBe('https://myclaw.163.com/claw/api/v1/agents/login');
101
+ return okResponse({ agent_name: 'remote-default' });
102
+ });
103
+ vi.stubGlobal('fetch', fetchMock);
104
+
105
+ await runSwitch('claw_remote_default');
106
+
107
+ const auth = readAuth();
108
+ expect(auth.activeProfile).toBe('remote-default');
109
+ expect(auth.profiles['remote-default']).toMatchObject({
110
+ agentName: 'remote-default',
111
+ apiKey: 'claw_remote_default',
112
+ serverUrl: 'https://myclaw.163.com/claw',
113
+ });
114
+ });
115
+
116
+ it('registers a new account with the bundled no-persona preset', async () => {
117
+ const fetchMock = vi.fn(async (url: string) => {
118
+ expect(url).toBe('https://myclaw.163.com/claw/api/v1/agents/register');
119
+ return okResponse({ api_key: 'claw_registered', agent_name: 'registered' });
120
+ });
121
+ vi.stubGlobal('fetch', fetchMock);
122
+
123
+ await createAccountCommand().parseAsync(['node', 'account', 'register', '--invite-code', 'invite-1'], { from: 'node' });
124
+
125
+ const auth = readAuth();
126
+ const profile: AuthProfile = auth.profiles.registered;
127
+ expect(profile).toMatchObject({
128
+ agentName: 'registered',
129
+ apiKey: 'claw_registered',
130
+ serverUrl: 'https://myclaw.163.com/claw',
131
+ });
132
+ expect(readFileSync(join(getUserDataAccountDir(dir, profile), 'persona.md'), 'utf8'))
133
+ .toBe(bundledDefaultPersona());
134
+ });
135
+
136
+ it('leaves local auth unchanged when server validation fails', async () => {
137
+ const store = new AuthStore();
138
+ store.addProfile({ agentName: 'local', apiKey: 'claw_local', serverUrl: 'https://example.com/claw' });
139
+ const before = readAuth();
140
+ vi.stubGlobal('fetch', vi.fn(async () => new Response(
141
+ JSON.stringify({ success: false, error: { code: '401001', message: 'API key not found' } }),
142
+ { status: 401, headers: { 'content-type': 'application/json' } },
143
+ )));
144
+
145
+ await expect(runSwitch('claw_missing')).rejects.toThrow('API error 401');
146
+
147
+ expect(readAuth()).toEqual(before);
148
+ });
149
+ });
@@ -10,7 +10,7 @@ import {
10
10
  noAccountMessage,
11
11
  registrationSuccessOutput,
12
12
  } from '../lib/account-guidance.js';
13
- import { ensureDefaultPersonaPlaceholder } from '../lib/persona.js';
13
+ import { ensureDefaultPersonaPreset } from '../lib/persona.js';
14
14
  import {
15
15
  normalizeCompetitionRankResponse,
16
16
  normalizeCompetitionStatusResponse,
@@ -39,6 +39,10 @@ function getRegisterServerUrl(env: NodeJS.ProcessEnv = process.env): string {
39
39
  return configured || DEFAULT_SERVER_URL;
40
40
  }
41
41
 
42
+ function getSwitchServerUrl(authStore: AuthStore, env: NodeJS.ProcessEnv = process.env): string {
43
+ return authStore.getActive()?.serverUrl ?? getRegisterServerUrl(env);
44
+ }
45
+
42
46
  async function buildCompetitionAccountInfo(client: GameClient): Promise<Record<string, any>> {
43
47
  let competition: Record<string, any>;
44
48
  try {
@@ -119,7 +123,7 @@ export function createAccountCommand(): Command {
119
123
  };
120
124
  authStore.addProfile(profile);
121
125
  try { createProfileDirs(profile); } catch {}
122
- ensureDefaultPersonaPlaceholder(authStore);
126
+ ensureDefaultPersonaPreset(authStore);
123
127
  console.log(JSON.stringify(registrationSuccessOutput(result, agentName), null, 2));
124
128
  });
125
129
 
@@ -128,15 +132,15 @@ export function createAccountCommand(): Command {
128
132
  .description('Rename agent (max once/month, max 2/year, not during a game)')
129
133
  .action(async (newName: string) => {
130
134
  const authStore = new AuthStore();
135
+ const activeKey = authStore.getActiveProfileKey();
131
136
  const profile = authStore.getActive();
132
137
  if (!profile) throw new Error('Not logged in.');
133
138
  const client = GameClient.fromAuth();
134
139
  const result = await client.renameAgent(newName);
135
140
  const oldName = profile.agentName;
136
141
  profile.agentName = newName;
137
- authStore.removeProfile(oldName);
142
+ if (activeKey) authStore.removeProfileByKey(activeKey);
138
143
  authStore.addProfile(profile);
139
- authStore.switchProfile(newName);
140
144
  console.log(JSON.stringify({ ...result, message: `Renamed "${oldName}" → "${newName}"` }, null, 2));
141
145
  });
142
146
 
@@ -144,14 +148,31 @@ export function createAccountCommand(): Command {
144
148
  .command('switch <apiKey>', { hidden: true })
145
149
  .description('Switch active profile by API key')
146
150
  .action(async (apiKey: string) => {
151
+ const targetApiKey = apiKey.trim();
152
+ if (!targetApiKey) throw new Error('API key is required.');
147
153
  const authStore = new AuthStore();
148
- const data = authStore.load();
149
- const profileKey = Object.keys(data.profiles).find(key => data.profiles[key]?.apiKey === apiKey);
150
- if (!profileKey) {
151
- throw new Error(`Profile with apiKey "${apiKey}" not found. Use \`clawclaw-cli account list\` to inspect saved accounts.`);
154
+ const profileKey = authStore.findProfileKeyByApiKey(targetApiKey);
155
+ if (profileKey) {
156
+ authStore.switchProfile(profileKey);
157
+ console.log(JSON.stringify({ message: 'Switched active profile', apiKey: targetApiKey }, null, 2));
158
+ return;
152
159
  }
153
- authStore.switchProfile(profileKey);
154
- console.log(JSON.stringify({ message: 'Switched active profile', apiKey }, null, 2));
160
+
161
+ const serverUrl = getSwitchServerUrl(authStore);
162
+ const client = new GameClient({ lobbyUrl: serverUrl, apiKey: '' });
163
+ const result = await client.login(targetApiKey);
164
+ const agentName = extractServerAccountName(result);
165
+ if (!agentName) throw new Error('Account switch failed: server did not return an agent name.');
166
+
167
+ const profile: AuthProfile = {
168
+ agentName,
169
+ apiKey: targetApiKey,
170
+ serverUrl,
171
+ };
172
+ authStore.addProfile(profile);
173
+ try { createProfileDirs(profile); } catch {}
174
+ ensureDefaultPersonaPreset(authStore);
175
+ console.log(JSON.stringify({ message: 'Imported and switched active profile', name: agentName, apiKey: targetApiKey }, null, 2));
155
176
  });
156
177
 
157
178
  account
@@ -1,5 +1,6 @@
1
1
  import { describe, expect, it } from 'vitest';
2
2
  import {
3
+ compactLatestEventForEvents,
3
4
  enrichEventsForState,
4
5
  enrichEventForEvents,
5
6
  selectMonitorEventRecordsAfterCursor,
@@ -98,3 +99,26 @@ describe('events command state enrichment', () => {
98
99
  expect(events[1]).not.toHaveProperty('players');
99
100
  });
100
101
  });
102
+
103
+ describe('events command latest-event formatting', () => {
104
+ it('compacts latest role_assigned payloads instead of returning task coordinates', () => {
105
+ const compact = compactLatestEventForEvents({
106
+ type: 'role_assigned',
107
+ tick: 0,
108
+ room: 'bar',
109
+ role: 'shrimp_generic',
110
+ role_display_name: 'Shrimp',
111
+ faction: 'lobster',
112
+ role_description: 'Do tasks.',
113
+ assigned_tasks: [
114
+ { name: 'Fix wire', room: 'engine', x: 1, y: 2, is_fake_shrimp: false },
115
+ ],
116
+ }, null);
117
+
118
+ expect(compact).toMatchObject({
119
+ type: 'role_assigned',
120
+ tasks: [{ name: 'Fix wire', room: 'engine' }],
121
+ });
122
+ expect(JSON.stringify(compact)).not.toMatch(/"(x|y)"\s*:/);
123
+ });
124
+ });
@@ -7,7 +7,7 @@ import { buildGameStartedEnrichment } from '../lib/game-context.js';
7
7
  import { getProfileStateDir } from '../lib/init-command.js';
8
8
  import { sendOwnerControlRequest } from '../runtime/owner-control.js';
9
9
  import { EventRecord, EventStore } from '../pipeline/event-store.js';
10
- import { compactEventFields, compactStateForEvents } from '../pipeline/event-format.js';
10
+ import { compactEventFields, compactEventForEvents, compactStateForEvents } from '../pipeline/event-format.js';
11
11
  import { NOTABLE_EVENT_TYPES, nextStepForTriggers } from './watch.js';
12
12
 
13
13
  interface EventsCommandOptions {
@@ -82,6 +82,13 @@ function eventTypes(records: EventRecord[]): string[] {
82
82
  return out;
83
83
  }
84
84
 
85
+ function cleanObject<T extends Record<string, any>>(obj: T): T {
86
+ for (const key of Object.keys(obj)) {
87
+ if (obj[key] === undefined) delete obj[key];
88
+ }
89
+ return obj;
90
+ }
91
+
85
92
  function latestEventRecord(records: EventRecord[], type: string): EventRecord | null {
86
93
  for (let i = records.length - 1; i >= 0; i -= 1) {
87
94
  const record = records[i];
@@ -143,14 +150,21 @@ async function enrichLatestEventForEvents(
143
150
  if (base.type !== 'game_started') return base;
144
151
  const enrichment = await readGameStartedEnrichment();
145
152
  if (!enrichment) return base;
146
- return {
153
+ return cleanObject({
147
154
  ...base,
148
155
  ...enrichment,
149
156
  map: {
150
157
  ...(base.map && typeof base.map === 'object' ? base.map : {}),
151
158
  ...(enrichment.map ?? {}),
152
159
  },
153
- };
160
+ });
161
+ }
162
+
163
+ export function compactLatestEventForEvents(
164
+ event: Record<string, any>,
165
+ summary: any | null | undefined,
166
+ ): Record<string, any> {
167
+ return compactEventForEvents(enrichEventForEvents(event, summary), { summary });
154
168
  }
155
169
 
156
170
  export function createEventsCommand(): Command {
@@ -192,9 +206,8 @@ export function createEventsCommand(): Command {
192
206
  query: { type: eventType },
193
207
  state,
194
208
  found: !!record,
195
- session_path: store.path,
196
209
  line: record?.line ?? null,
197
- event,
210
+ event: event ? compactLatestEventForEvents(event, summary) : null,
198
211
  }, null, 2));
199
212
  return;
200
213
  }
@@ -211,7 +224,6 @@ export function createEventsCommand(): Command {
211
224
  exit_reason: triggers,
212
225
  next_step: nextStepForTriggers(triggers),
213
226
  mode: 'tail',
214
- session_path: store.path,
215
227
  cursor: null,
216
228
  counts: { returned: records.length },
217
229
  events: records.map((record) => compactEventFields(
@@ -3,6 +3,7 @@ import { mkdtempSync, rmSync, writeFileSync, readFileSync } from 'fs';
3
3
  import { tmpdir } from 'os';
4
4
  import { join } from 'path';
5
5
  import { AuthStore } from './auth.js';
6
+ import { getUserDataAccountHash } from './user-data.js';
6
7
 
7
8
  describe('AuthStore', () => {
8
9
  let dir: string;
@@ -44,6 +45,49 @@ describe('AuthStore', () => {
44
45
  expect(runtime.profiles['lobster-1']).toBeUndefined();
45
46
  });
46
47
 
48
+ it('keeps same-name profiles under distinct stable keys', () => {
49
+ const store = new AuthStore(authFile);
50
+ store.addProfile({ agentName: 'lobster', apiKey: 'claw_1', serverUrl: 'https://example.com' });
51
+ const secondKey = store.addProfile({ agentName: 'lobster', apiKey: 'claw_2', serverUrl: 'https://example.com' });
52
+
53
+ const raw = JSON.parse(readFileSync(authFile, 'utf8'));
54
+ expect(raw.profiles.lobster.apiKey).toBe('claw_1');
55
+ expect(secondKey).toBe(`lobster#${getUserDataAccountHash('claw_2')}`);
56
+ expect(raw.profiles[secondKey].apiKey).toBe('claw_2');
57
+ expect(raw.activeProfile).toBe(secondKey);
58
+ });
59
+
60
+ it('reuses the existing profile key for the same apiKey', () => {
61
+ const store = new AuthStore(authFile);
62
+ const firstKey = store.addProfile({ agentName: 'lobster', apiKey: 'claw_1', serverUrl: 'https://example.com' });
63
+ const secondKey = store.addProfile({ agentName: 'renamed-lobster', apiKey: 'claw_1', serverUrl: 'https://example.com' });
64
+
65
+ const raw = JSON.parse(readFileSync(authFile, 'utf8'));
66
+ expect(firstKey).toBe('lobster');
67
+ expect(secondKey).toBe('lobster');
68
+ expect(Object.keys(raw.profiles)).toEqual(['lobster']);
69
+ expect(raw.profiles.lobster.agentName).toBe('renamed-lobster');
70
+ });
71
+
72
+ it('gets and removes profiles by active key', () => {
73
+ const runtimeFile = join(dir, 'auth-state.json');
74
+ const store = new AuthStore(authFile, runtimeFile);
75
+ store.addProfile({ agentName: 'lobster', apiKey: 'claw_1', serverUrl: 'https://example.com' });
76
+ const secondKey = store.addProfile({ agentName: 'lobster', apiKey: 'claw_2', serverUrl: 'https://example.com' });
77
+ store.updateGameServerUrl('https://example.com/gs/current');
78
+
79
+ expect(store.getActiveProfileKey()).toBe(secondKey);
80
+ expect(store.findProfileKeyByApiKey('claw_2')).toBe(secondKey);
81
+
82
+ store.removeProfileByKey(secondKey);
83
+
84
+ const raw = JSON.parse(readFileSync(authFile, 'utf8'));
85
+ const runtime = JSON.parse(readFileSync(runtimeFile, 'utf8'));
86
+ expect(raw.profiles.lobster.apiKey).toBe('claw_1');
87
+ expect(raw.profiles[secondKey]).toBeUndefined();
88
+ expect(runtime.profiles[secondKey]).toBeUndefined();
89
+ });
90
+
47
91
  it('strips legacy TTS fields when normalizing auth data', () => {
48
92
  writeFileSync(authFile, JSON.stringify({
49
93
  activeProfile: 'lobster-1',
package/src/lib/auth.ts CHANGED
@@ -4,6 +4,7 @@ import { getWorkspaceDir } from './init-command.js';
4
4
  import {
5
5
  ensureUserDataLayout,
6
6
  getRuntimeAuthStateFile,
7
+ getUserDataAccountHash,
7
8
  getUserDataAuthFile,
8
9
  readRuntimeAuthState,
9
10
  splitAuthData,
@@ -27,6 +28,24 @@ export interface AuthData {
27
28
 
28
29
  const EMPTY_AUTH: AuthData = { activeProfile: '', profiles: {} };
29
30
 
31
+ function profileKeyFor(data: AuthData, profile: Pick<AuthProfile, 'agentName' | 'apiKey'>): string {
32
+ for (const [key, savedProfile] of Object.entries(data.profiles ?? {})) {
33
+ if (savedProfile?.apiKey === profile.apiKey) return key;
34
+ }
35
+
36
+ const baseKey = profile.agentName;
37
+ if (!data.profiles[baseKey]) return baseKey;
38
+
39
+ const suffix = getUserDataAccountHash(profile.apiKey);
40
+ let candidate = `${baseKey}#${suffix}`;
41
+ let index = 2;
42
+ while (data.profiles[candidate] && data.profiles[candidate]?.apiKey !== profile.apiKey) {
43
+ candidate = `${baseKey}#${suffix}-${index}`;
44
+ index += 1;
45
+ }
46
+ return candidate;
47
+ }
48
+
30
49
  export class AuthStore {
31
50
  private authFile: string;
32
51
  private runtimeAuthStateFile: string;
@@ -82,24 +101,30 @@ export class AuthStore {
82
101
  if (changed) writeRuntimeAuthState(this.runtimeAuthStateFile, current);
83
102
  }
84
103
 
85
- addProfile(profile: AuthProfile): void {
104
+ addProfile(profile: AuthProfile): string {
86
105
  const data = this.load();
87
- data.profiles[profile.agentName] = profile;
88
- data.activeProfile = profile.agentName;
106
+ const key = profileKeyFor(data, profile);
107
+ data.profiles[key] = profile;
108
+ data.activeProfile = key;
89
109
  this.save(data);
110
+ return key;
90
111
  }
91
112
 
92
113
  removeProfile(name: string): void {
114
+ this.removeProfileByKey(name);
115
+ }
116
+
117
+ removeProfileByKey(key: string): void {
93
118
  const data = this.load();
94
- delete data.profiles[name];
95
- if (data.activeProfile === name) {
119
+ delete data.profiles[key];
120
+ if (data.activeProfile === key) {
96
121
  const remaining = Object.keys(data.profiles);
97
122
  data.activeProfile = remaining[0] ?? '';
98
123
  }
99
124
  this.save(data);
100
125
  const state = readRuntimeAuthState(this.runtimeAuthStateFile);
101
- if (state.profiles[name]) {
102
- delete state.profiles[name];
126
+ if (state.profiles[key]) {
127
+ delete state.profiles[key];
103
128
  writeRuntimeAuthState(this.runtimeAuthStateFile, state);
104
129
  }
105
130
  }
@@ -117,6 +142,17 @@ export class AuthStore {
117
142
  return Object.keys(this.load().profiles);
118
143
  }
119
144
 
145
+ findProfileKeyByApiKey(apiKey: string): string | null {
146
+ const data = this.load();
147
+ return Object.keys(data.profiles).find(key => data.profiles[key]?.apiKey === apiKey) ?? null;
148
+ }
149
+
150
+ getActiveProfileKey(): string | null {
151
+ const data = this.load();
152
+ if (!data.activeProfile || !data.profiles[data.activeProfile]) return null;
153
+ return data.activeProfile;
154
+ }
155
+
120
156
  getActive(): AuthProfile | null {
121
157
  const data = this.load();
122
158
  if (!data.activeProfile || !data.profiles[data.activeProfile]) return null;
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, it, beforeEach, afterEach } from 'vitest';
2
- import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'fs';
2
+ import { existsSync, mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'fs';
3
3
  import { tmpdir } from 'os';
4
4
  import { join } from 'path';
5
5
  import { AuthStore, type AuthData } from './auth.js';
@@ -49,4 +49,14 @@ describe('loadContext', () => {
49
49
  expect(snapshot.persona.path.split('\\').join('/')).toContain('user-data/accounts/');
50
50
  expect(snapshot.memory.path.split('\\').join('/')).toContain('user-data/accounts/');
51
51
  });
52
+
53
+ it('does not create a default persona while loading context', () => {
54
+ rmSync(join(dir, 'accounts', 'claw_test_key_12345678', 'persona.md'), { force: true });
55
+
56
+ const snapshot = loadContext(new AuthStore());
57
+
58
+ expect(snapshot.persona.exists).toBe(false);
59
+ expect(snapshot.persona.content).toBe('');
60
+ expect(existsSync(snapshot.persona.path)).toBe(false);
61
+ });
52
62
  });
@@ -1,11 +1,7 @@
1
1
  import { existsSync, readFileSync, writeFileSync } from 'fs';
2
2
  import { AuthStore } from './auth.js';
3
3
  import { getProfileMemoryFile } from './init-command.js';
4
- import {
5
- ensureDefaultPersonaPlaceholder,
6
- getActivePersonaFile,
7
- readPersonaFile,
8
- } from './persona.js';
4
+ import { getActivePersonaFile, readPersonaFile } from './persona.js';
9
5
 
10
6
  export interface LoadedFileSnapshot {
11
7
  path: string;
@@ -46,7 +42,6 @@ export function loadMemorySnapshot(authStore = new AuthStore()): LoadedFileSnaps
46
42
  }
47
43
 
48
44
  export function loadContext(authStore = new AuthStore()): LoadContextSnapshot {
49
- ensureDefaultPersonaPlaceholder(authStore);
50
45
  return {
51
46
  persona: loadPersonaSnapshot(authStore),
52
47
  memory: loadMemorySnapshot(authStore),
@@ -5,7 +5,7 @@ import { join } from 'path';
5
5
  import { AuthStore } from './auth.js';
6
6
  import { CLAWCLAW_WORKSPACE_DIR } from './init-command.js';
7
7
  import {
8
- ensureDefaultPersonaPlaceholder,
8
+ ensureDefaultPersonaPreset,
9
9
  applyPersonaPreset,
10
10
  findPersonaPreset,
11
11
  listPersonaPresets,
@@ -61,9 +61,9 @@ describe('persona presets', () => {
61
61
  expect(readFileSync(target, 'utf8')).toBe('wild');
62
62
  });
63
63
 
64
- it('applies the default placeholder when the active account persona is empty', () => {
64
+ it('applies the default preset when the active account persona is empty', () => {
65
65
  writeFileSync(join(dir, '无人设.md'), 'plain');
66
- const result = ensureDefaultPersonaPlaceholder(createActiveStore(), dir);
66
+ const result = ensureDefaultPersonaPreset(createActiveStore(), dir);
67
67
 
68
68
  expect(result.applied).toBe(true);
69
69
  expect(result.preset.name).toBe('无人设');
@@ -73,10 +73,10 @@ describe('persona presets', () => {
73
73
  it('keeps existing active account persona content', () => {
74
74
  writeFileSync(join(dir, '无人设.md'), 'plain');
75
75
  const store = createActiveStore();
76
- const first = ensureDefaultPersonaPlaceholder(store, dir);
76
+ const first = ensureDefaultPersonaPreset(store, dir);
77
77
  writeFileSync(first.path, 'voice');
78
78
 
79
- const result = ensureDefaultPersonaPlaceholder(store, dir);
79
+ const result = ensureDefaultPersonaPreset(store, dir);
80
80
 
81
81
  expect(result.applied).toBe(false);
82
82
  expect(readFileSync(result.path, 'utf8')).toBe('voice');
@@ -69,7 +69,7 @@ export function applyPersonaPreset(name: string, targetPath: string, dir = getBu
69
69
  return preset;
70
70
  }
71
71
 
72
- export function ensureDefaultPersonaPlaceholder(authStore = new AuthStore(), dir = getBundledPersonaDir()): { path: string; preset: PersonaPreset; applied: boolean } {
72
+ export function ensureDefaultPersonaPreset(authStore = new AuthStore(), dir = getBundledPersonaDir()): { path: string; preset: PersonaPreset; applied: boolean } {
73
73
  const path = getActivePersonaFile(authStore);
74
74
  const current = readPersonaFile(path);
75
75
  if (current.trim() !== '') {