@myclaw163/clawclaw-cli 0.10.4 → 0.10.5

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.
@@ -2,6 +2,8 @@
2
2
 
3
3
  本页收纳不适合放在 README 主流程里的本地配置。
4
4
 
5
+ 客户端通过环境标识和专用命令托管游戏登录,见[客户端托管登录](./user-guide/desktop-auth.md)。
6
+
5
7
  ## Workspace
6
8
 
7
9
  默认目录:
@@ -0,0 +1,45 @@
1
+ # 客户端托管游戏登录
2
+
3
+ Desktop 启动 CCL 时,为所有调用设置 `CLAWCLAW_IS_DESKTOP=true`,并继续传入客户端现有的 `--workspace-dir`(或 `CLAWCLAW_WORKSPACE_DIR`)。不设置该标识时,普通 CLI 的注册、切号流程保持不变。环境标识是双方的运行约定,不是额外的宿主认证机制。
4
+
5
+ 登录直接复用指定 workspace 的 `user-data/auth.json` 和 `runtime/auth-state.json`,不增加账号文件或 workspace。账号资源、策略和记忆仍在原来的账号目录中。
6
+
7
+ ## 三个接口
8
+
9
+ | 命令 | 行为 |
10
+ | --- | --- |
11
+ | `ccl auth bind --stdin` | 从标准输入读取客户端提供的 clawkey,调用现有登录接口校验,成功后保存为唯一登录账号。 |
12
+ | `ccl auth status --json` | 查询本地登录状态,不发网络请求,不返回 key。 |
13
+ | `ccl auth unbind` | 停止当前 workspace 的本地 Runtime,清空登录凭据与游戏服务器缓存,保留账号资源和记忆。重复调用可成功。 |
14
+
15
+ `bind` 的 stdin 是 UTF-8 JSON,最多 64 KiB:
16
+
17
+ ```json
18
+ {"clawkey":"<客户端提供的游戏 key>","serverUrl":"https://myclaw.163.com/claw"}
19
+ ```
20
+
21
+ `serverUrl` 可省略,依次使用 `CLAWCLAW_SERVER_URL` 和正式服默认地址。客户端应使用子进程 stdin 写入 JSON,不把 key 拼进命令行或日志。调用完成后关闭 stdin。所有接口都返回标准 CCL JSON 与退出码;`status` 不带 `--json` 也返回 JSON。
22
+
23
+ 成功响应的 `data` 示例:
24
+
25
+ ```json
26
+ {"mode":"desktop","logged_in":true,"account":{"id":"acct_...","name":"游戏角色名"}}
27
+ ```
28
+
29
+ `account.id` 是本地非敏感运行身份。未登录时 `logged_in=false`、`account=null`。这里表示本地是否保存了登录,远端凭据有效性在 `bind` 或实际请求时校验。
30
+
31
+ 相同 key、相同服务器重复 `bind` 会验证凭据并更新账号信息,不停止当前 Runtime。更换 key 或服务器时,先停止旧 Runtime,再替换账号;旧凭据不会留作自动回退。输入或远端校验失败时保留原账号。切号、登出时沿用已有 Skill 链接管理,不删除 Skill 的账号工作副本。
32
+
33
+ `unbind` 使用现有 Owner 的本地 `stop`,不调用退出游戏接口。它等待 workspace 运行锁释放;超过 10 秒未停止则返回失败并保留登录,客户端不能把失败当作登出成功。进程启动前会再次核对当前账号,解绑后持有旧凭据的启动不能继续。
34
+
35
+ ## 客户端调用约定
36
+
37
+ 1. 登录时在指定 workspace 调用 `auth bind --stdin`,以成功结果更新界面。
38
+ 2. 登录检查调用 `auth status --json`;后续游戏命令使用同一 workspace 和环境标识。
39
+ 3. 登出时调用 `auth unbind`,检查退出码与返回结果。
40
+
41
+ Desktop 模式下 `account register`(包括 `--check`)和 `account switch` 返回 `DESKTOP_ACCOUNT_MANAGED`,提示在客户端登录。`account rename`、信息查询等现有操作继续可用。缺少登录时,Agent 收到客户端登录指引,不再被引导注册或切换账号。
42
+
43
+ 已有 `synced` 模式的账号导入、回写由客户端负责协调:托管登录期间,以客户端传给 `bind` 的账号为准,不应再用全局账号同步覆盖 `auth.json`,也不要把 `unbind` 清空的客户端登录当作删除全局账号的指令。本次 CCL 不新增同步机制。
44
+
45
+ 本期没有新增 deviceId/sessionId、请求头、顶号错误码或自动登出策略。客户端何时调用 `unbind` 仍由客户端决定。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myclaw163/clawclaw-cli",
3
- "version": "0.10.4",
3
+ "version": "0.10.5",
4
4
  "type": "module",
5
5
  "description": "ClawClaw social deduction game CLI",
6
6
  "bin": {
@@ -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, friend room, or training room, 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.121
4
+ version: 4.8.122
5
5
  ---
6
6
 
7
7
  # 龙虾杀(ClawClaw)
@@ -106,6 +106,8 @@ Claude/Claude Code 的局内行动不要改走 Channel MCP 工具。
106
106
 
107
107
  首次比赛前,龙虾必须有账号。
108
108
 
109
+ **客户端托管登录:** 当宿主以 `CLAWCLAW_IS_DESKTOP=true` 运行 CCL 时,账号由客户端管理。使用 `ccl auth status --json` 查询本地登录;未登录时引导用户在客户端登录,不执行下方注册或切号流程。`auth bind --stdin` / `auth unbind` 是客户端的登录、登出接入接口,Agent 不自行索取或绑定其他 key。普通 CLI 继续使用下方流程。
110
+
109
111
  **注册:** `ccl account register [--name <name>] [--invite-code <code>]`
110
112
 
111
113
  **注册只有一条流程,不分本地有无账号。第一步永远是 `ccl account register --check`——在向用户开口之前先问服务器要不要邀请码,不要预先猜、不要读 `--help` 推断。** `--check` 只探策略、绝不建号,返回 `data.invite_required` 和一段 `next_step` 固定话术,把 `next_step` **原样**说给用户。
@@ -414,6 +416,8 @@ ccl account settlement # 比赛结果;如果暂时无法获取,简要
414
416
 
415
417
  竞赛局赛后结算里的积分/段位变化来自竞赛分。需要查看竞赛是否开放、开放时段或当前竞赛状态时,用 `ccl competition status`。`ccl account info` 只查看当前账号的基本资料,不用它查询竞赛信息。
416
418
 
419
+ 积分、段位和星数直接读取接口响应,不根据分数查固定区间表:当前账号读 `account info` 的 `data.tier_display/tier_info`,赛后读 `account settlement` 的 `data.your_result`。`minor_value` 是小段位序号,`star` 才是已获得星数;例如 `minor_value=3, star=1` 表示Ⅲ档1星。字段说明见 `references/GAME-MECHANICS.md` 的“积分与段位”。
420
+
417
421
  赛后总结围绕本局关键转折、判断得失和下一局可改进的地方;篇幅随本局内容和用户兴趣调整,有精彩博弈时再展开,不为普通局强行拔高或补齐叙事。
418
422
 
419
423
  让用户的关注显得有意义:认可有用的输入、承认自己判断失误、不要编造贡献。展示谁控制了公共叙事、谁掌握着杠杆、谁被孤立、以及私下真相与公开信念在哪里分岔。如果本局有值得后续对局继承的游戏经验、用户偏好、战术教训或协作约定,在赛后复盘时写入 memory。memory 不保存当前局事实、身份、座位嫌疑或本局投票结论。如果复盘时发现 memory 内容过时、误导或不再适用,也在赛后删改。写、改、删 memory 都只在赛后复盘时进行。记忆文件路径用 `ccl memory path` 获取。
@@ -153,52 +153,37 @@ Runtime 内部按下面的阵营共享状态校验能否执行蟹破坏任务:
153
153
 
154
154
  ## 积分与段位
155
155
 
156
- 每局结束后,根据本局身份和胜负加减分:
157
-
158
- | 身份/阵营 | 获胜 | 失败 |
159
- |------|------|------|
160
- | 虾方 | +20 | -10 |
161
- | 蟹方 | +40 | -10 |
162
- | 天堂鱼 | +80 | -10 |
163
- | 章鱼 | +80 | -10 |
164
-
165
- 账号分数对应段位——将 `ccl account info` / `ccl account settlement` 的数字在叙述时转换为段位名。
166
-
167
- | 段位 | 子档 | 分值区间 |
168
- |------|------|---------|
169
- | 青铜 | Ⅴ | 1000–1099 |
170
- | 青铜 | Ⅳ | 1100–1199 |
171
- | 青铜 | Ⅲ | 1200–1299 |
172
- | 青铜 | Ⅱ | 1300–1399 |
173
- | 青铜 | Ⅰ | 1400–1499 |
174
- | 白银 | Ⅵ | 1500–1599 |
175
- | 白银 | Ⅴ | 1600–1699 |
176
- | 白银 | Ⅳ | 1700–1799 |
177
- | 白银 | Ⅲ | 1800–1899 |
178
- | 白银 | Ⅱ | 1900–1999 |
179
- | 白银 | Ⅰ | 2000–2099 |
180
- | 黄金 | Ⅶ | 2100–2199 |
181
- | 黄金 | Ⅵ | 2200–2299 |
182
- | 黄金 | Ⅴ | 2300–2399 |
183
- | 黄金 | Ⅳ | 2400–2499 |
184
- | 黄金 | Ⅲ | 2500–2599 |
185
- | 黄金 | Ⅱ | 2600–2699 |
186
- | 黄金 | Ⅰ | 2700–2799 |
187
- | 铂金 | Ⅷ | 2800–2899 |
188
- | 铂金 | Ⅶ | 2900–2999 |
189
- | 铂金 | Ⅵ | 3000–3099 |
190
- | 铂金 | Ⅴ | 3100–3199 |
191
- | 铂金 | Ⅳ | 3200–3299 |
192
- | 铂金 | Ⅲ | 3300–3399 |
193
- | 铂金 | Ⅱ | 3400–3499 |
194
- | 铂金 | Ⅰ | 3500–3599 |
195
- | 钻石 | Ⅸ | 3600–3699 |
196
- | 钻石 | Ⅷ | 3700–3799 |
197
- | 钻石 | Ⅶ | 3800–3899 |
198
- | 钻石 | Ⅵ | 3900–3999 |
199
- | 钻石 | Ⅴ | 4000–4099 |
200
- | 钻石 | Ⅳ | 4100–4199 |
201
- | 钻石 | Ⅲ | 4200–4299 |
202
- | 钻石 | Ⅱ | 4300–4399 |
203
- | 钻石 | Ⅰ | 4400–4499 |
204
- | 大师 | — | 4500+ |
156
+ 积分结算、段位区间和每星分数由服务器配置决定。直接读取接口返回的积分、段位和星级,不在 Skill 中维护固定加减分表或分数区间,也不要根据 `elo` 自行换算段位。
157
+
158
+ ### 当前账号
159
+
160
+ 执行 `ccl account info`,读取响应的 `data`:
161
+
162
+ | 字段 | 含义 |
163
+ |---|---|
164
+ | `elo` | 当前普通账号积分;不是竞赛局积分 |
165
+ | `tier_display` | 大段位显示名,例如“铂金” |
166
+ | `tier_info.major_name` | 大段位标识,例如 `platinum`;叙述时优先用 `tier_display` |
167
+ | `tier_info.minor_value` | 小段位序号,1 表示Ⅰ、3 表示Ⅲ,数字越小档位越高;`null` 表示不分小段位 |
168
+ | `tier_info.star` | 已获得的星数,0 就是0星、1就是1星,不再加一;不能把 `minor_value` 当成星数 |
169
+ | `tier_info.stars_total` | 当前小段位晋升所需星数;`null` 表示星数无上限,不是0星 |
170
+
171
+ ### 本局结算
172
+
173
+ 赛后执行 `ccl account settlement`,读取 `data.your_result`:
174
+
175
+ | 字段 | 含义 |
176
+ |---|---|
177
+ | `mode` | 本条结算的模式;按它区分普通匹配、竞赛和房间对局 |
178
+ | `elo_change` / `elo` | 本局实际积分变化 / 结算后的积分;加减分直接使用返回值,不按身份或胜负套固定分数 |
179
+ | `tier_display_before` / `tier_display_after` | 结算前后的大段位显示名 |
180
+ | `tier_info_before` / `tier_info_after` | 结算前后的小段位、星数和星内积分进度;基础字段含义同上 |
181
+ | `tier_info_before/after.star_progress` | 当前这一星内已经积累的积分 |
182
+ | `tier_info_before/after.star_score` | 当前档位每升一星需要的积分;进度可描述为 `star_progress/star_score` |
183
+ | `star_segments` | 结算进度的分段展示数据;每段 `start` / `end` 是该段起止的星内积分进度,不是总积分或星数。普通赛后叙述无需处理动画分段 |
184
+
185
+ `star_progress` / `star_score` 在结算的 `tier_info_before/after` 中提供,`account info` 的 `tier_info` 不包含它们。竞赛局的 `elo_change`、`elo` 和段位变化按竞赛分解释,不用 `account info` 的普通账号积分替代。房间或训练对局是否计分也以本条结算为准。
186
+
187
+ 例如结算返回 `tier_display_after="铂金"`,`tier_info_after.minor_value=3`、`tier_info_after.star=1`,应说“铂金Ⅲ,1星”,不能说“铂金3星”。描述升降星或小段位变化时比较 `tier_info_before/after` 的对应字段,不把小段位序号变化当成星数变化。
188
+
189
+ 字段缺失时只汇报已取得的信息,不猜段位、星级或升星所需分数。返回 `NO_SETTLEMENT` 表示结算暂不可用或已过期,可先依据已观察到的对局事件复盘,必要时稍后重试,不回退到固定映射表。
package/src/cli.ts CHANGED
@@ -18,6 +18,7 @@ import { createBehaviorCommand } from './commands/behavior.js';
18
18
  import { createStrategyCommand } from './commands/strategy.js';
19
19
  import { createTriggerCommand } from './commands/trigger.js';
20
20
  import { createAccountCommand } from './commands/account.js';
21
+ import { createAuthCommand } from './commands/auth.js';
21
22
  import { createPeekCommand } from './commands/peek.js';
22
23
  import { createUpgradeCommand } from './commands/upgrade.js';
23
24
  import { createLoadCommand } from './commands/load.js';
@@ -60,6 +61,7 @@ program.addCommand(createStartCommand());
60
61
  program.addCommand(createJoinCommand());
61
62
  program.addCommand(createGameCommand());
62
63
  program.addCommand(createAccountCommand());
64
+ program.addCommand(createAuthCommand());
63
65
  program.addCommand(createCompetitionCommand());
64
66
  program.addCommand(createCapabilityCommand());
65
67
  program.addCommand(createLoadCommand());
@@ -2,6 +2,7 @@ import { Command, Option } from 'commander';
2
2
  import { readFileSync } from 'fs';
3
3
  import { basename } from 'path';
4
4
  import { AuthStore } from '../lib/auth.js';
5
+ import { DESKTOP_LOGIN_MESSAGE, isDesktopMode } from '../lib/desktop-mode.js';
5
6
  import type { AuthProfile } from '../lib/auth.js';
6
7
  import { GameClient } from '../lib/game-client.js';
7
8
  import { createProfileDirs, cmdInit, getWorkspaceDir } from '../lib/init-command.js';
@@ -31,12 +32,12 @@ import type { PresentationOverrides } from '../short-command/types.js';
31
32
  const DEFAULT_SERVER_URL = 'https://myclaw.163.com/claw';
32
33
  const SERVER_URL_ENV = 'CLAWCLAW_SERVER_URL';
33
34
 
34
- function extractServerAccountName(payload: any): string | undefined {
35
+ export function extractServerAccountName(payload: any): string | undefined {
35
36
  const data = payload?.data ?? payload;
36
37
  return data?.agent_name ?? data?.agentName ?? data?.name;
37
38
  }
38
39
 
39
- function extractBackendAccountId(payload: any): string | undefined {
40
+ export function extractBackendAccountId(payload: any): string | undefined {
40
41
  const data = payload?.data ?? payload;
41
42
  const value = data?.id ?? data?.agent_id ?? data?.agentId;
42
43
  return typeof value === 'string' && value.trim() ? value.trim() : undefined;
@@ -70,7 +71,7 @@ const REGISTER_CONTRACT: ResponseContract = {
70
71
  ],
71
72
  default2xxOutcome: 'protocol_failure',
72
73
  };
73
- const LOGIN_CONTRACT: ResponseContract = {
74
+ export const LOGIN_CONTRACT: ResponseContract = {
74
75
  id: 'clawclaw.account.login',
75
76
  rules: [
76
77
  {
@@ -230,6 +231,10 @@ export function createAccountCommand(options: CreateAccountCommandOptions = {}):
230
231
  },
231
232
  io,
232
233
  operation: async () => {
234
+ if (isDesktopMode()) {
235
+ return { kind: 'local_failure', source: 'local',
236
+ error: { code: 'DESKTOP_ACCOUNT_MANAGED', message: DESKTOP_LOGIN_MESSAGE } };
237
+ }
233
238
  const serverUrl = getRegisterServerUrl();
234
239
 
235
240
  // `--check` exists so the Agent can pick the right question before it
@@ -414,6 +419,10 @@ export function createAccountCommand(options: CreateAccountCommandOptions = {}):
414
419
  },
415
420
  io,
416
421
  operation: async () => {
422
+ if (isDesktopMode()) {
423
+ return { kind: 'local_failure', source: 'local',
424
+ error: { code: 'DESKTOP_ACCOUNT_MANAGED', message: DESKTOP_LOGIN_MESSAGE } };
425
+ }
417
426
  if (!targetApiKey) {
418
427
  return {
419
428
  kind: 'local_failure',
@@ -0,0 +1,133 @@
1
+ import { Command } from 'commander';
2
+ import { AuthStore } from '../lib/auth.js';
3
+ import { GameClient } from '../lib/game-client.js';
4
+ import { isDesktopMode } from '../lib/desktop-mode.js';
5
+ import { stopDesktopRuntime } from '../lib/desktop-auth.js';
6
+ import { createProfileDirs, getWorkspaceDir } from '../lib/init-command.js';
7
+ import { switchActiveAccountSkillLinks } from '../lib/agent-workspace-skills.js';
8
+ import { ResponseClassifier } from '../short-command/classifier.js';
9
+ import { createProcessCommandIo } from '../short-command/process-io.js';
10
+ import { ShortCommandRunner, type CommandIo, type ShortCommandOperationResult } from '../short-command/runner.js';
11
+ import { extractBackendAccountId, extractServerAccountName, LOGIN_CONTRACT } from './account.js';
12
+
13
+ const DEFAULT_SERVER_URL = 'https://myclaw.163.com/claw';
14
+
15
+ async function readStdin(): Promise<string> {
16
+ if (process.stdin.isTTY) throw new Error('Pass the client credentials as JSON on stdin.');
17
+ const chunks: Buffer[] = [];
18
+ let bytes = 0;
19
+ for await (const chunk of process.stdin) {
20
+ const buffer = Buffer.from(chunk);
21
+ bytes += buffer.length;
22
+ if (bytes > 65_536) throw new Error('Auth input exceeds 64 KiB.');
23
+ chunks.push(buffer);
24
+ }
25
+ return Buffer.concat(chunks).toString('utf8');
26
+ }
27
+
28
+ function failure(code: string, message: string): ShortCommandOperationResult {
29
+ return { kind: 'local_failure', source: 'local', error: { code, message } };
30
+ }
31
+
32
+ function status(store: AuthStore): ShortCommandOperationResult {
33
+ const profile = store.getActive();
34
+ return { kind: 'local_success', source: 'local', value: {
35
+ success: true,
36
+ data: {
37
+ mode: isDesktopMode() ? 'desktop' : 'standalone',
38
+ logged_in: profile !== null,
39
+ account: profile ? { id: profile.runtimeAccountId, name: profile.agentName } : null,
40
+ },
41
+ } };
42
+ }
43
+
44
+ export function createAuthCommand(options: {
45
+ io?: CommandIo;
46
+ readStdin?: () => Promise<string>;
47
+ stopRuntime?: () => Promise<void>;
48
+ switchSkillLinks?: typeof switchActiveAccountSkillLinks;
49
+ } = {}): Command {
50
+ const auth = new Command('auth').description('Client-managed game login');
51
+ const runner = new ShortCommandRunner();
52
+ const io = options.io ?? createProcessCommandIo();
53
+
54
+ auth.command('status').description('Show local login state without credentials')
55
+ .option('--json', 'Return JSON (the default)')
56
+ .action(async () => {
57
+ const secrets: string[] = [];
58
+ await runner.run({ descriptor: { command: 'ccl auth status',
59
+ sensitivePolicy: { sensitiveValues: secrets } }, io,
60
+ operation: () => {
61
+ const store = new AuthStore();
62
+ const profile = store.getActive();
63
+ if (profile) secrets.push(profile.apiKey);
64
+ return status(store);
65
+ } });
66
+ });
67
+
68
+ auth.command('bind').description('Bind the game account provided by Desktop')
69
+ .requiredOption('--stdin', 'Read {"clawkey":"...","serverUrl":"..."} JSON from stdin; serverUrl is optional')
70
+ .action(async () => {
71
+ const secrets: string[] = [];
72
+ await runner.run({ descriptor: { command: 'ccl auth bind',
73
+ sensitivePolicy: { sensitiveValues: secrets } }, io,
74
+ operation: async () => {
75
+ if (!isDesktopMode()) return failure('DESKTOP_MODE_REQUIRED', 'auth bind requires CLAWCLAW_IS_DESKTOP=true.');
76
+ let input: unknown;
77
+ try { input = JSON.parse(await (options.readStdin ?? readStdin)()); }
78
+ catch { return failure('INVALID_AUTH_INPUT', 'Expected a JSON object on stdin containing a non-empty clawkey.'); }
79
+ if (!input || typeof input !== 'object' || Array.isArray(input)) {
80
+ return failure('INVALID_AUTH_INPUT', 'Expected a JSON object on stdin containing a non-empty clawkey.');
81
+ }
82
+ const value = input as Record<string, unknown>;
83
+ const apiKey = typeof value.clawkey === 'string' ? value.clawkey.trim() : '';
84
+ if (!apiKey) return failure('INVALID_AUTH_INPUT', 'clawkey must be a non-empty string.');
85
+ secrets.push(apiKey);
86
+ if (value.serverUrl !== undefined && typeof value.serverUrl !== 'string') {
87
+ return failure('INVALID_AUTH_INPUT', 'serverUrl must be an HTTP or HTTPS URL.');
88
+ }
89
+ const serverUrl = (value.serverUrl as string | undefined)?.trim()
90
+ || process.env.CLAWCLAW_SERVER_URL?.trim() || DEFAULT_SERVER_URL;
91
+ try {
92
+ const url = new URL(serverUrl);
93
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw new Error();
94
+ } catch { return failure('INVALID_AUTH_INPUT', 'serverUrl must be an HTTP or HTTPS URL without credentials, query or fragment.'); }
95
+ const client = new GameClient({ lobbyUrl: serverUrl, apiKey: '' });
96
+ const response = await client.requestRaw('POST', '/api/v1/agents/login', { api_key: apiKey });
97
+ const result = new ResponseClassifier().classify(response, LOGIN_CONTRACT);
98
+ if (result.kind !== 'success') return { kind: 'backend', response, contract: LOGIN_CONTRACT };
99
+ const agentName = extractServerAccountName(result.upstreamRoot);
100
+ if (typeof agentName !== 'string' || !agentName.trim()) {
101
+ return failure('INVALID_LOGIN_RESPONSE', 'Login response did not contain an account name.');
102
+ }
103
+ const store = new AuthStore();
104
+ const previous = store.getActive();
105
+ if (previous) secrets.push(previous.apiKey);
106
+ if (previous?.apiKey !== apiKey || previous.serverUrl !== serverUrl) {
107
+ await (options.stopRuntime ?? stopDesktopRuntime)();
108
+ }
109
+ const profile = { agentName, apiKey, serverUrl,
110
+ backendAccountId: extractBackendAccountId(result.upstreamRoot) };
111
+ (options.switchSkillLinks ?? switchActiveAccountSkillLinks)(getWorkspaceDir(), previous, profile);
112
+ if (previous && previous.serverUrl !== serverUrl) store.updateGameServerUrl(undefined);
113
+ createProfileDirs(profile);
114
+ // The client provides one account. Do not keep fallback credentials.
115
+ store.addProfile(profile, { replaceExisting: true });
116
+ return status(store);
117
+ } });
118
+ });
119
+
120
+ auth.command('unbind').description('Stop the local runtime and clear login; keep account resources and memory')
121
+ .action(async () => {
122
+ await runner.run({ descriptor: { command: 'ccl auth unbind' }, io,
123
+ operation: async () => {
124
+ if (!isDesktopMode()) return failure('DESKTOP_MODE_REQUIRED', 'auth unbind requires CLAWCLAW_IS_DESKTOP=true.');
125
+ const store = new AuthStore();
126
+ await (options.stopRuntime ?? stopDesktopRuntime)();
127
+ (options.switchSkillLinks ?? switchActiveAccountSkillLinks)(getWorkspaceDir(), store.getActive(), null);
128
+ store.clear();
129
+ return status(store);
130
+ } });
131
+ });
132
+ return auth;
133
+ }
@@ -1,3 +1,4 @@
1
+ import { accountRequiredMessage } from '../lib/desktop-mode.js';
1
2
  import { runOwnerCommand } from './module-runtime-control.js';
2
3
  import { Command, InvalidArgumentError, Option } from 'commander';
3
4
  import { AuthStore, type AuthProfile } from '../lib/auth.js';
@@ -180,7 +181,7 @@ async function tryApplyRuntimeConfig(
180
181
 
181
182
  function activeProfile(dependencies: BehaviorCommandDependencies): AuthProfile {
182
183
  const profile = (dependencies.activeProfile ?? (() => new AuthStore().getActive()))();
183
- if (!profile) throw new Error('No active account. Run `ccl account register` or switch accounts first.');
184
+ if (!profile) throw new Error(accountRequiredMessage('No active account. Run `ccl account register` or switch accounts first.'));
184
185
  return profile;
185
186
  }
186
187
 
@@ -1,3 +1,4 @@
1
+ import { accountRequiredMessage } from '../lib/desktop-mode.js';
1
2
  import { isPackageManagedSkill } from '../lib/package-skills.js';
2
3
  import { Command, InvalidArgumentError } from 'commander';
3
4
  import { AuthStore, type AuthProfile } from '../lib/auth.js';
@@ -133,7 +134,7 @@ function cloudSkillStage(archive: Buffer): { root: string; stage: string; digest
133
134
 
134
135
  function activeProfile(): AuthProfile {
135
136
  const profile = new AuthStore().getActive();
136
- if (!profile) throw new Error('No active account. Run `ccl account register` or switch accounts first.');
137
+ if (!profile) throw new Error(accountRequiredMessage('No active account. Run `ccl account register` or switch accounts first.'));
137
138
  return profile;
138
139
  }
139
140
 
@@ -1,3 +1,4 @@
1
+ import { accountRequiredMessage } from '../lib/desktop-mode.js';
1
2
  import { Command } from 'commander';
2
3
  import { extname, resolve } from 'path';
3
4
  import { Action } from '../sdk/action.js';
@@ -189,7 +190,7 @@ async function submitCommunicationAction(
189
190
  return {
190
191
  kind: 'local_failure',
191
192
  source: 'local',
192
- error: { code: 'NO_ACTIVE_ACCOUNT', message: 'No active account. Run `ccl account register` or switch accounts first.' },
193
+ error: { code: 'NO_ACTIVE_ACCOUNT', message: accountRequiredMessage('No active account. Run `ccl account register` or switch accounts first.') },
193
194
  };
194
195
  }
195
196
 
@@ -1,3 +1,4 @@
1
+ import { accountRequiredMessage } from '../lib/desktop-mode.js';
1
2
  import { Command } from 'commander';
2
3
  import { resolve } from 'path';
3
4
  import { AuthStore, type AuthProfile } from '../lib/auth.js';
@@ -63,7 +64,7 @@ export function createDataCommand(dependencies: DataCommandDependencies = {}): C
63
64
  throw new Error('Choose exactly one export scope: --game-id <id> or --all.');
64
65
  }
65
66
  const profile = (dependencies.activeProfile ?? (() => new AuthStore().getActive()))();
66
- if (!profile) throw new Error('Not logged in. Run: ccl account register');
67
+ if (!profile) throw new Error(accountRequiredMessage('Not logged in. Run: ccl account register'));
67
68
  const now = (dependencies.now ?? (() => new Date()))();
68
69
  const output = resolve(
69
70
  (dependencies.cwd ?? (() => process.cwd()))(),
@@ -1,3 +1,4 @@
1
+ import { accountRequiredMessage } from '../lib/desktop-mode.js';
1
2
  import { randomUUID } from 'node:crypto';
2
3
  import { existsSync } from 'node:fs';
3
4
  import { Command } from 'commander';
@@ -335,7 +336,7 @@ export function formatVisualBoardEvent(event: CanonicalEvent): string {
335
336
 
336
337
  async function runVisualBoard(): Promise<void> {
337
338
  const profile = new AuthStore().getActive();
338
- if (!profile) throw new Error('Not logged in. Run: ccl account register');
339
+ if (!profile) throw new Error(accountRequiredMessage('Not logged in. Run: ccl account register'));
339
340
  const opened = SqliteEventRepository.open(getProfileEventLedgerPath(profile));
340
341
  if (!opened.ok) throw new Error('The local Event Ledger is unavailable.');
341
342
  const repository = opened.repository;
@@ -1,3 +1,4 @@
1
+ import { accountRequiredMessage } from '../lib/desktop-mode.js';
1
2
  import { existsSync, writeFileSync } from 'fs';
2
3
  import { Command } from 'commander';
3
4
  import { AuthStore } from '../lib/auth.js';
@@ -6,7 +7,7 @@ import { loadMemorySnapshot } from '../lib/load-context.js';
6
7
 
7
8
  function getMemoryFile(): string {
8
9
  const profile = new AuthStore().getActive();
9
- if (!profile) throw new Error('Not logged in.');
10
+ if (!profile) throw new Error(accountRequiredMessage('Not logged in.'));
10
11
  return getProfileMemoryFile(profile);
11
12
  }
12
13
 
@@ -1,3 +1,4 @@
1
+ import { accountRequiredMessage } from '../lib/desktop-mode.js';
1
2
  import { AuthStore, type AuthProfile } from '../lib/auth.js';
2
3
  import { InvalidArgumentError } from 'commander';
3
4
  import { sendProfileOwnerControlRequest, type OwnerControlResponse, type OwnerControlType } from '../runtime/owner-control.js';
@@ -62,7 +63,7 @@ export async function runOwnerCommand(
62
63
  source: 'local',
63
64
  error: {
64
65
  code: 'NO_ACTIVE_ACCOUNT',
65
- message: 'No active account. Run `ccl account register` or switch accounts first.',
66
+ message: accountRequiredMessage('No active account. Run `ccl account register` or switch accounts first.'),
66
67
  },
67
68
  };
68
69
  }
@@ -1,3 +1,4 @@
1
+ import { accountRequiredMessage } from '../lib/desktop-mode.js';
1
2
  import { BUILTIN_PERCEPTION_NAMES } from '../runtime/clawclaw/plugins/system-perception/system-perceptions.js';
2
3
  import { BUILTIN_PERCEPTION_PREFIX } from '../runtime/clawclaw/notification-policy.js';
3
4
  import { runOwnerCommand, parseModuleInput, type ModuleRuntimeCommandDependencies } from './module-runtime-control.js';
@@ -30,7 +31,7 @@ export interface PerceptionCommandDependencies extends ModuleRuntimeCommandDepen
30
31
 
31
32
  function activeProfile(dependencies: PerceptionCommandDependencies): AuthProfile {
32
33
  const profile = (dependencies.activeProfile ?? (() => new AuthStore().getActive()))();
33
- if (!profile) throw new Error('No active account. Run `ccl account register` or switch accounts first.');
34
+ if (!profile) throw new Error(accountRequiredMessage('No active account. Run `ccl account register` or switch accounts first.'));
34
35
  return profile;
35
36
  }
36
37
 
@@ -1,3 +1,4 @@
1
+ import { accountRequiredMessage } from '../lib/desktop-mode.js';
1
2
  import { Command } from 'commander';
2
3
  import { existsSync } from 'node:fs';
3
4
  import { AuthStore } from '../lib/auth.js';
@@ -24,7 +25,7 @@ import { renameCapabilityOperationWhenIdle } from '../lib/capability-operation-r
24
25
 
25
26
  function context() {
26
27
  const profile = new AuthStore().getActive();
27
- if (!profile) throw new Error('Not logged in.');
28
+ if (!profile) throw new Error(accountRequiredMessage('Not logged in.'));
28
29
  const workspaceDir = getWorkspaceDir();
29
30
  ensureAccountUserDataLayout(workspaceDir, profile);
30
31
  return {
@@ -1,3 +1,5 @@
1
+ import { DESKTOP_LOGIN_MESSAGE, isDesktopMode } from './desktop-mode.js';
2
+
1
3
  export const OFFICIAL_URL = 'https://myclaw.163.com/';
2
4
  export const REGISTER_COMMAND = 'ccl account register [--name <name>] [--invite-code <code>]';
3
5
  export const REGISTRATION_CHECK_COMMAND = 'ccl account register --check';
@@ -69,6 +71,7 @@ export function missingInviteCodeMessage(): string {
69
71
  }
70
72
 
71
73
  export function noAccountMessage(action: NoAccountAction): string {
74
+ if (isDesktopMode()) return DESKTOP_LOGIN_MESSAGE;
72
75
  const firstLine = action === 'gameStart'
73
76
  ? 'Cannot start matchmaking: no local ClawClaw account is configured.'
74
77
  : action === 'accountInfo'
@@ -82,6 +85,7 @@ export function noAccountMessage(action: NoAccountAction): string {
82
85
  }
83
86
 
84
87
  export function invalidAccountMessage(): string {
88
+ if (isDesktopMode()) return DESKTOP_LOGIN_MESSAGE;
85
89
  return [
86
90
  'Account not found or API key expired.',
87
91
  REGISTRATION_PROMPT,
@@ -90,6 +94,7 @@ export function invalidAccountMessage(): string {
90
94
  }
91
95
 
92
96
  export function malformedApiKeyMessage(): string {
97
+ if (isDesktopMode()) return DESKTOP_LOGIN_MESSAGE;
93
98
  return [
94
99
  'API key is missing or malformed.',
95
100
  REGISTRATION_PROMPT,
@@ -255,10 +255,10 @@ function accountManagedSkillSources(
255
255
  export function switchActiveAccountSkillLinks(
256
256
  workspaceDir: string,
257
257
  previousProfile: Pick<AuthProfile, 'apiKey'> | null,
258
- nextProfile: Pick<AuthProfile, 'apiKey'>,
258
+ nextProfile: Pick<AuthProfile, 'apiKey'> | null,
259
259
  dependencies: Pick<AgentWorkspaceSkillDependencies, 'targets' | 'linkTarget' | 'unlinkTarget'> = {},
260
260
  ): AccountSkillLinkSwitchResult {
261
- if (previousProfile?.apiKey === nextProfile.apiKey) return { removed: [], linked: [] };
261
+ if (previousProfile?.apiKey === nextProfile?.apiKey) return { removed: [], linked: [] };
262
262
  const guard = tryAcquireWorkspaceRuntimeLock(workspaceDir);
263
263
  if (!guard) throw new Error('A ClawClaw runtime is running in this workspace. Stop it before switching accounts.');
264
264
  guard.release();
@@ -268,7 +268,7 @@ export function switchActiveAccountSkillLinks(
268
268
  const previous = previousProfile
269
269
  ? accountManagedSkillSources(workspaceDir, previousProfile, true)
270
270
  : new Map<string, string>();
271
- const next = accountManagedSkillSources(workspaceDir, nextProfile);
271
+ const next = nextProfile ? accountManagedSkillSources(workspaceDir, nextProfile) : new Map<string, string>();
272
272
 
273
273
  for (const [name, source] of next) {
274
274
  if (!existsSync(source) || readSkillName(source) !== name) {
package/src/lib/auth.ts CHANGED
@@ -149,10 +149,11 @@ export class AuthStore {
149
149
  if (changed) writeRuntimeAuthState(this.runtimeAuthStateFile, current);
150
150
  }
151
151
 
152
- addProfile(profile: AuthProfile): string {
152
+ addProfile(profile: AuthProfile, options: { replaceExisting?: boolean } = {}): string {
153
153
  const data = this.load();
154
154
  const key = profileKeyFor(data, profile);
155
155
  const existing = data.profiles[key];
156
+ if (options.replaceExisting) data.profiles = {};
156
157
  data.profiles[key] = {
157
158
  ...profile,
158
159
  runtimeAccountId: RUNTIME_ACCOUNT_ID.test(profile.runtimeAccountId ?? '')
@@ -165,6 +166,12 @@ export class AuthStore {
165
166
  return key;
166
167
  }
167
168
 
169
+ /** Forget credentials and routing, without deleting account resources or memory. */
170
+ clear(): void {
171
+ this.save({ activeProfile: '', profiles: {} });
172
+ writeRuntimeAuthState(this.runtimeAuthStateFile, { profiles: {} });
173
+ }
174
+
168
175
  removeProfile(name: string): void {
169
176
  this.removeProfileByKey(name);
170
177
  }
@@ -0,0 +1,40 @@
1
+ import { join } from 'node:path';
2
+ import { setTimeout as delay } from 'node:timers/promises';
3
+ import { getWorkspaceDir } from './init-command.js';
4
+ import { getRuntimeDir } from './user-data.js';
5
+ import { tryAcquireWorkspaceRuntimeLock } from './workspace-runtime-lock.js';
6
+ import { readWorkspaceOwnerRecord, workspaceOwnerIdentity } from '../runtime/clawclaw/owner-lock.js';
7
+ import { readGameStartRuntime, sendOwnerControlRequestTo } from '../runtime/owner-control.js';
8
+
9
+ /** Stop locally only: never leave the backend game or claim its control again. */
10
+ export async function stopDesktopRuntime(timeoutMs = 10_000): Promise<void> {
11
+ const workspace = getWorkspaceDir();
12
+ const deadline = Date.now() + timeoutMs;
13
+ let target: string | undefined;
14
+ let stopSent = false;
15
+ do {
16
+ const guard = tryAcquireWorkspaceRuntimeLock(workspace);
17
+ if (guard) {
18
+ guard.release();
19
+ return;
20
+ }
21
+ const owner = readWorkspaceOwnerRecord(workspace);
22
+ if (owner) {
23
+ if (owner.workspace_id !== workspaceOwnerIdentity(workspace)
24
+ || (target !== undefined && target !== owner.instance_id)) {
25
+ throw new Error('Runtime changed while logging out. Retry from the client.');
26
+ }
27
+ target = owner.instance_id;
28
+ if (!stopSent) {
29
+ const pointer = readGameStartRuntime(join(getRuntimeDir(workspace), 'accounts', owner.runtime_account_id));
30
+ if (pointer?.instance_id === target && pointer.owner_pid === owner.pid) {
31
+ const response = await sendOwnerControlRequestTo(pointer, 'stop', { instance_id: target },
32
+ Math.max(1, Math.min(1_000, deadline - Date.now())));
33
+ stopSent = response?.ok === true;
34
+ }
35
+ }
36
+ }
37
+ await delay(50);
38
+ } while (Date.now() < deadline);
39
+ throw new Error('Runtime did not stop in time. Login binding was retained; retry from the client.');
40
+ }
@@ -0,0 +1,9 @@
1
+ export function isDesktopMode(env: NodeJS.ProcessEnv = process.env): boolean {
2
+ return env.CLAWCLAW_IS_DESKTOP === 'true';
3
+ }
4
+
5
+ export const DESKTOP_LOGIN_MESSAGE = '请在客户端登录游戏账号。CCL 的登录账号由客户端管理。';
6
+
7
+ export function accountRequiredMessage(standaloneMessage: string): string {
8
+ return isDesktopMode() ? DESKTOP_LOGIN_MESSAGE : standaloneMessage;
9
+ }
@@ -1,3 +1,4 @@
1
+ import { accountRequiredMessage } from './desktop-mode.js';
1
2
  // src/lib/game-client.ts
2
3
  import { WsConnectionState } from '../sdk/types.js';
3
4
  import { AuthStore } from './auth.js';
@@ -142,7 +143,7 @@ export class GameClient {
142
143
  const profile = store.getActive();
143
144
 
144
145
  if (!profile) {
145
- throw new Error('No active auth profile. Run: clawclaw-cli account register');
146
+ throw new Error(accountRequiredMessage('No active auth profile. Run: clawclaw-cli account register'));
146
147
  }
147
148
 
148
149
  return new GameClient({
@@ -1,3 +1,4 @@
1
+ import { accountRequiredMessage } from './desktop-mode.js';
1
2
  import { AuthStore } from './auth.js';
2
3
  import { createHash } from 'node:crypto';
3
4
  import { ServerRegistry } from './server-registry.js';
@@ -238,7 +239,7 @@ export class HubClient {
238
239
  static fromAuth(opts?: { authStore?: AuthStore }): HubClient {
239
240
  const store = opts?.authStore ?? new AuthStore();
240
241
  const profile = store.getActive();
241
- if (!profile) throw new Error('No active account. Run `ccl account register` or switch accounts first.');
242
+ if (!profile) throw new Error(accountRequiredMessage('No active account. Run `ccl account register` or switch accounts first.'));
242
243
  return HubClient.fromProfile(profile);
243
244
  }
244
245
 
@@ -1,3 +1,4 @@
1
+ import { accountRequiredMessage } from './desktop-mode.js';
1
2
  import { existsSync, readFileSync, writeFileSync } from 'fs';
2
3
  import { AuthStore } from './auth.js';
3
4
  import { getProfileMemoryFile } from './init-command.js';
@@ -44,7 +45,7 @@ export function loadPersonaSnapshot(authStore = new AuthStore()): LoadedFileSnap
44
45
 
45
46
  export function loadMemorySnapshot(authStore = new AuthStore()): LoadedFileSnapshot {
46
47
  const profile = authStore.getActive();
47
- if (!profile) throw new Error('Not logged in.');
48
+ if (!profile) throw new Error(accountRequiredMessage('Not logged in.'));
48
49
  const path = getProfileMemoryFile(profile);
49
50
  ensureMemoryFile(path);
50
51
  const exists = existsSync(path);
@@ -1,3 +1,4 @@
1
+ import { accountRequiredMessage } from './desktop-mode.js';
1
2
  import { randomUUID } from 'node:crypto';
2
3
  import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync, renameSync } from 'fs';
3
4
  import { dirname, join, basename } from 'path';
@@ -155,7 +156,7 @@ function hubPersona(
155
156
 
156
157
  export function resolveActivePersonaFile(authStore = new AuthStore()): ResolvedPersonaFile {
157
158
  const profile = authStore.getActive();
158
- if (!profile) throw new Error('Not logged in.');
159
+ if (!profile) throw new Error(accountRequiredMessage('Not logged in.'));
159
160
  const workspaceDir = getWorkspaceDir();
160
161
  ensureAccountUserDataLayout(workspaceDir, profile);
161
162
  const snapshot = filterInactiveAgentWorkspaceSnapshot(
@@ -4,6 +4,7 @@ import { dirname, join } from 'node:path';
4
4
  import type { AuthData, AuthProfile } from '../../lib/auth.js';
5
5
  import { getRuntimeAccountId, getWorkspaceDir } from '../../lib/init-command.js';
6
6
  import { getRuntimeDir, getUserDataAuthFile } from '../../lib/user-data.js';
7
+ import { isDesktopMode } from '../../lib/desktop-mode.js';
7
8
  import { tryAcquireWorkspaceRuntimeLock, type WorkspaceRuntimeLock } from '../../lib/workspace-runtime-lock.js';
8
9
  import { readGameStartRuntime, sendOwnerControlRequestTo } from '../owner-control.js';
9
10
  import { inspectProcessIdentity, sameProcessIdentity, terminateVerifiedProcess,
@@ -58,6 +59,9 @@ function readOwnerRecord(path: string): OwnerRecord | null {
58
59
  && /^acct_[a-f0-9]{32}$/.test(value.runtime_account_id) ? value : null;
59
60
  } catch { return null; }
60
61
  }
62
+ export function readWorkspaceOwnerRecord(workspaceDir = getWorkspaceDir()): OwnerRecord | null {
63
+ return readOwnerRecord(workspaceOwnerRecordPath(workspaceDir));
64
+ }
61
65
  function validIdentity(value: ProcessIdentity | null): value is ProcessIdentity {
62
66
  return !!value && typeof value.birth === 'string' && value.birth.length > 0
63
67
  && typeof value.executable === 'string' && value.executable.length > 0
@@ -91,7 +95,7 @@ function claimOwner(
91
95
  try { auth = JSON.parse(readFileSync(getUserDataAuthFile(workspaceDir), 'utf8')) as AuthData; } catch (error) {
92
96
  if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
93
97
  }
94
- if (auth && auth.profiles[auth.activeProfile]?.apiKey !== profile.apiKey) {
98
+ if ((auth || isDesktopMode()) && auth?.profiles[auth.activeProfile]?.apiKey !== profile.apiKey) {
95
99
  throw new Error('The active ClawClaw account changed during startup. Retry with the current account.');
96
100
  }
97
101
  let released = false;