@myclaw163/clawclaw-cli 0.8.15 → 0.8.16

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.8.15",
3
+ "version": "0.8.16",
4
4
  "type": "module",
5
5
  "description": "ClawClaw social deduction game CLI",
6
6
  "bin": {
@@ -1,21 +1,19 @@
1
1
  import {
2
2
  cpSync,
3
3
  existsSync,
4
- lstatSync,
5
4
  mkdirSync,
6
5
  readFileSync,
7
- realpathSync,
8
6
  renameSync,
9
7
  rmSync,
10
- symlinkSync,
11
- unlinkSync,
12
8
  } from 'node:fs';
13
- import { createHash, randomUUID } from 'node:crypto';
9
+ import { spawnSync } from 'node:child_process';
10
+ import { randomUUID } from 'node:crypto';
14
11
  import { homedir } from 'node:os';
15
- import { basename, dirname, join, resolve, win32 } from 'node:path';
12
+ import { basename, dirname, join, resolve } from 'node:path';
16
13
  import { fileURLToPath, pathToFileURL } from 'node:url';
17
14
 
18
15
  const SKILL_NAME = 'clawclaw';
16
+ const SKILLS_ADD_TIMEOUT_MS = 60_000;
19
17
 
20
18
  function getOpenClawSkillsDir(homeDir = homedir()) {
21
19
  for (const dir of ['.openclaw', '.clawdbot', '.moltbot']) {
@@ -37,33 +35,7 @@ function defaultCandidateSkillDirs() {
37
35
  ];
38
36
  }
39
37
 
40
- function defaultWorkspaceDir() {
41
- const configured = process.env.CLAWCLAW_WORKSPACE_DIR?.trim();
42
- if (configured) return resolve(configured);
43
- if (process.platform === 'win32') {
44
- return win32.join(process.env.APPDATA ?? win32.join(homedir(), 'AppData', 'Roaming'), 'clawclaw');
45
- }
46
- return join(homedir(), '.clawclaw');
47
- }
48
-
49
- function activeProfile(workspaceDir) {
50
- const authPath = join(workspaceDir, 'user-data', 'auth.json');
51
- if (!existsSync(authPath)) return undefined;
52
- try {
53
- const auth = JSON.parse(readFileSync(authPath, 'utf8'));
54
- const key = auth.activeProfile;
55
- const profile = key && auth.profiles?.[key];
56
- return profile?.apiKey ? profile : undefined;
57
- } catch {
58
- return undefined;
59
- }
60
- }
61
-
62
- function accountHash(apiKey) {
63
- return createHash('sha256').update(apiKey).digest('hex').slice(0, 16);
64
- }
65
-
66
- function replaceCanonical(source, target) {
38
+ function replaceTarget(source, target) {
67
39
  const stage = `${target}.ccl-stage-${randomUUID()}`;
68
40
  const displaced = `${target}.ccl-old-${randomUUID()}`;
69
41
  let moved = false;
@@ -85,16 +57,13 @@ function replaceCanonical(source, target) {
85
57
  }
86
58
  }
87
59
 
88
- function linkTarget(source, target) {
89
- mkdirSync(dirname(target), { recursive: true });
90
- if (existsSync(target)) {
91
- if (!lstatSync(target).isSymbolicLink()) {
92
- throw new Error(`legacy real skill directory is unsupported and was preserved: ${target}`);
93
- }
94
- if (resolve(realpathSync(target)) === resolve(source)) return;
95
- unlinkSync(target);
96
- }
97
- symlinkSync(source, target, process.platform === 'win32' ? 'junction' : 'dir');
60
+ function resolveSkillsBin(installDir) {
61
+ const packagePath = resolve(installDir, 'node_modules', 'skills', 'package.json');
62
+ if (!existsSync(packagePath)) throw new Error(`skills package not found: ${packagePath}`);
63
+ const pkg = JSON.parse(readFileSync(packagePath, 'utf8'));
64
+ const entry = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.skills;
65
+ if (!entry) throw new Error('skills package has no bin entry');
66
+ return resolve(installDir, 'node_modules', 'skills', entry);
98
67
  }
99
68
 
100
69
  export function syncBundledSkill(options = {}) {
@@ -105,22 +74,24 @@ export function syncBundledSkill(options = {}) {
105
74
  const installDir = resolve(options.installDir ?? join(scriptDir, '..'));
106
75
  const sourceDir = resolve(installDir, 'skills', SKILL_NAME);
107
76
  if (!existsSync(sourceDir)) throw new Error(`bundled skill dir not found: ${sourceDir}`);
108
- const workspaceDir = resolve(options.workspaceDir ?? defaultWorkspaceDir());
109
- const profile = options.profile ?? activeProfile(workspaceDir);
110
- if (!profile?.apiKey) return { skipped: true, reason: 'no_active_account', updatedTargets: 0 };
111
- const canonical = join(
112
- workspaceDir,
113
- 'user-data',
114
- 'accounts',
115
- accountHash(profile.apiKey),
116
- 'capabilities',
117
- 'skills',
118
- SKILL_NAME,
77
+ const spawn = options.spawnSync ?? spawnSync;
78
+ const result = spawn(
79
+ process.execPath,
80
+ [resolveSkillsBin(installDir), 'add', sourceDir, '-y', '-g'],
81
+ {
82
+ cwd: installDir,
83
+ timeout: SKILLS_ADD_TIMEOUT_MS,
84
+ windowsHide: true,
85
+ stdio: options.stdio ?? 'inherit',
86
+ },
119
87
  );
120
- replaceCanonical(sourceDir, canonical);
88
+ if (result.error) throw result.error;
89
+ if (typeof result.status === 'number' && result.status !== 0) {
90
+ throw new Error(`skills add exited with code ${result.status}`);
91
+ }
121
92
  const targets = options.candidateDirs ?? defaultCandidateSkillDirs();
122
- for (const target of targets) linkTarget(canonical, resolve(target));
123
- return { skipped: false, canonical, updatedTargets: targets.length };
93
+ for (const target of targets) replaceTarget(sourceDir, resolve(target));
94
+ return { skipped: false, updatedTargets: targets.length };
124
95
  }
125
96
 
126
97
  function formatFailure(error) {
@@ -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.94
4
+ version: 4.8.95
5
5
  ---
6
6
 
7
7
  # 龙虾杀(ClawClaw)
@@ -106,7 +106,7 @@ Claude/Claude Code 的局内行动不要改走 Channel MCP 工具。
106
106
 
107
107
  **人设:** 注册流程不追问人设;新账号默认使用“无人设”预设。用户主动要求更换人设时,再按 `references/COMMANDS.md` 的人设选择流程处理。
108
108
 
109
- **多终端:** 能力工作副本按账号隔离在 `accounts/<account-hash>/capabilities/`。各终端独立执行 `ccl load`,不要求自动合并;未修改旧版跟随云端,本地修改不会被远端覆盖。旧 `local/hub` 目录不迁移。Skill 只有账号 canonical 副本,`.agents/.claude/.codex/.openclaw` 都是当前 active 账号的软链接。
109
+ **多终端:** 能力工作副本按账号隔离在 `accounts/<account-hash>/capabilities/`。各终端独立执行 `ccl load`,不要求自动合并;未修改旧版跟随云端,本地修改不会被远端覆盖。旧 `local/hub` 目录不迁移。Hub/本地 Skill 只有账号 canonical 副本,`.agents/.claude/.codex/.openclaw` 都链接到当前 active 账号;切换账号时先移除旧账号链接,再建立新账号链接。官方 `clawclaw` 主 Skill 由已安装的 CCL 包直接同步到各宿主目录,不进入账号 canonical 或 Hub 软链接流程。
110
110
 
111
111
  ### 3.2 赛前介绍
112
112
 
@@ -44,7 +44,7 @@ ccl trigger enable <id> # 启用并尝试热应用到当前
44
44
  ccl trigger disable <id> # 禁用并尝试热应用到当前 Runtime
45
45
  ```
46
46
 
47
- `ccl load` 返回紧凑的 `ccl.load.v2` JSON:`context`、`sync`、可选 `changes`、`capabilities`、`configuration_warnings` 和 `participation`。`changes.cloud_sync` 是自动上传结果,`capabilities.selection_required` 是只需选择一次的本地装配项。`capabilities.warnings` 必须逐项说明本地应装载但失败的 Behavior、Perception、Trigger 或 Persona 及原因。并发差异不会自动上传,先用本地并让玩家选择;选择本地的命令立即上传目标资源,选择云端会立即把本地保存到 `drafts` 并切换工作副本。`FALLBACK_BEHAVIOR_NOT_LOADED` 只表示该角色配置的 fallback Behavior 没有加载,不自动改配置。这些命令只静态读取 Manifest,绝不 import 或执行源码;可用清单不代表模块已经运行。
47
+ `ccl load` 返回紧凑的 `ccl.load.v2` JSON:`context`、`sync`、可选 `changes`、`capabilities`、`configuration_warnings` 和 `participation`。`changes.cloud_sync` 是自动上传结果;其中 `skipped[].reason=local_origin_unrecognized` 表示本地副本缺少可信来源基线,继续使用但不自动上传。`capabilities.selection_required` 是只需选择一次的本地装配项。`capabilities.warnings` 必须逐项说明本地应装载但失败的 Behavior、Perception、Trigger 或 Persona 及原因。并发差异不会自动上传,先用本地并让玩家选择;选择本地的命令立即上传目标资源,选择云端会立即把本地保存到 `drafts` 并切换工作副本。`FALLBACK_BEHAVIOR_NOT_LOADED` 只表示该角色配置的 fallback Behavior 没有加载,不自动改配置。这些命令只静态读取 Manifest,绝不 import 或执行源码;可用清单不代表模块已经运行。
48
48
 
49
49
  执行 `ccl capability equip`、`unequip`、`resolve --use local` 或 `resolve --use cloud` 后,修改本身已经生效,但 Agent 在任何 `start`、`join` 或好友房开局操作前必须再运行一次完整 `ccl load`,以最终输出刷新上下文、同步结果、能力清单和 participation。`resolve --use later` 不修改有效内容,不触发这条复核要求。
50
50
 
@@ -20,10 +20,11 @@ ccl hub sync <type>/<resource-id> --json
20
20
 
21
21
  - `hub install`:加入云端 Workspace,不自动装配。
22
22
  - Hub 页面选择:写入当前 Loadout。
23
- - `ccl load`:读取当前 Loadout,并在本地/base/remote 三方比较后决定实际内容。未修改的线上旧版跟随 Hub 更新;玩家本地修改优先使用,并由 CCL 自动创建私有版本或 fork。
23
+ - `ccl load`:读取当前 Loadout,并对 Strategy、Perception、Persona 和普通 Hub Skill 统一执行本地/base/remote 三方比较。未修改的线上旧版跟随 Hub 更新;具有可信基线的玩家本地修改优先使用,并由 CCL 自动创建私有版本或 fork。缺少可信本地来源基线的副本继续在本地使用,但不会自动上传。
24
24
  - 纯本地主目录中的合法能力自动创建私有 v1,不自动公开或装配云端副本。`drafts` 永不自动上传。
25
25
  - 并发差异不自动上传;Agent 让玩家选择本地、云端或暂不处理。选择本地的命令立即只上传目标资源,选择云端的命令立即把本地修改保存为草稿并切换工作副本。
26
26
  - `ccl capability equip` 和 `ccl capability unequip` 立即保存本地装配状态;Skill 同时立即更新四个宿主链接。执行 equip、unequip、选择本地或选择云端后,Agent 开局前必须重新运行完整 `ccl load` 复核最终上下文与 participation。选择 later 不修改内容,不要求因此重复 load。
27
+ - 官方 `clawclaw` 主 Skill 由已安装的 CCL 包直接同步到宿主目录,不属于账号级 Hub Skill,不参与账号 canonical 软链接、三方比较或云端上传。
27
28
  - `hub sync`:把一个已安装 Workspace 项切到市场当前公开版本;之后仍由 `ccl load` 应用。
28
29
 
29
30
  ## 0.8.x Strategy
@@ -15,6 +15,7 @@ import {
15
15
  registrationCheckOutput,
16
16
  } from '../lib/account-guidance.js';
17
17
  import { fetchServerStatus, resolveInviteRequired } from '../lib/server-status.js';
18
+ import { switchActiveAccountSkillLinks } from '../lib/agent-workspace-skills.js';
18
19
  import { ResponseClassifier } from '../short-command/classifier.js';
19
20
  import { createProcessCommandIo } from '../short-command/process-io.js';
20
21
  import { booleanSuccessContract } from '../short-command/response-contract.js';
@@ -194,6 +195,7 @@ function buildRegistrationForm(opts: {
194
195
 
195
196
  export interface CreateAccountCommandOptions {
196
197
  io?: CommandIo;
198
+ switchSkillLinks?: typeof switchActiveAccountSkillLinks;
197
199
  }
198
200
 
199
201
  export function createAccountCommand(options: CreateAccountCommandOptions = {}): Command {
@@ -414,6 +416,24 @@ export function createAccountCommand(options: CreateAccountCommandOptions = {}):
414
416
 
415
417
  const profileKey = authStore.findProfileKeyByApiKey(targetApiKey);
416
418
  if (profileKey) {
419
+ const previous = authStore.getActive();
420
+ const target = authStore.load().profiles[profileKey]!;
421
+ try {
422
+ (options.switchSkillLinks ?? switchActiveAccountSkillLinks)(
423
+ cmdInit().path,
424
+ previous,
425
+ target,
426
+ );
427
+ } catch (error) {
428
+ return {
429
+ kind: 'local_failure',
430
+ source: 'local',
431
+ error: {
432
+ code: 'ACCOUNT_SKILL_LINK_SWITCH_FAILED',
433
+ message: error instanceof Error ? error.message : String(error),
434
+ },
435
+ };
436
+ }
417
437
  authStore.switchProfile(profileKey);
418
438
  const active = authStore.getActive();
419
439
  return {
@@ -451,6 +471,22 @@ export function createAccountCommand(options: CreateAccountCommandOptions = {}):
451
471
  serverUrl,
452
472
  backendAccountId: extractBackendAccountId(root),
453
473
  };
474
+ try {
475
+ (options.switchSkillLinks ?? switchActiveAccountSkillLinks)(
476
+ cmdInit().path,
477
+ authStore.getActive(),
478
+ profile,
479
+ );
480
+ } catch (error) {
481
+ return {
482
+ kind: 'local_failure',
483
+ source: 'local',
484
+ error: {
485
+ code: 'ACCOUNT_SKILL_LINK_SWITCH_FAILED',
486
+ message: error instanceof Error ? error.message : String(error),
487
+ },
488
+ };
489
+ }
454
490
  authStore.addProfile(profile);
455
491
  try { createProfileDirs(profile); } catch {}
456
492
  return backendResult(response, LOGIN_CONTRACT, {
@@ -128,7 +128,11 @@ function parseRef(value: string): { type: CapabilityWorkspaceType; id: string }
128
128
  if (!match) {
129
129
  throw new InvalidArgumentError('expected <behavior|perception|persona|skill>/<id>');
130
130
  }
131
- return { type: match[1] as CapabilityWorkspaceType, id: match[2]! };
131
+ const parsed = { type: match[1] as CapabilityWorkspaceType, id: match[2]! };
132
+ if (parsed.type === 'skill' && parsed.id === 'clawclaw') {
133
+ throw new InvalidArgumentError('The official clawclaw Skill is managed by the installed CCL package');
134
+ }
135
+ return parsed;
132
136
  }
133
137
 
134
138
  function applySkillSelection(
@@ -330,6 +334,7 @@ export function createCapabilityCommand(dependencies: CapabilityCommandDependenc
330
334
  baseSha256: digest,
331
335
  lastUploadedSha256: digest,
332
336
  observedCloudVersionId: undefined,
337
+ localOriginUnrecognized: undefined,
333
338
  });
334
339
  setCapabilityConflictChoice(workspaceDir, profile, entry.key, undefined);
335
340
  console.log(JSON.stringify({
@@ -277,6 +277,9 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
277
277
  workspaceItemId: item.workspaceItemId,
278
278
  publisher: item.hub?.publisher ?? 'community',
279
279
  baseSha256: item.sourceFiles[0]?.sha256,
280
+ localOriginUnrecognized: item.resolution === 'local_origin_unrecognized'
281
+ ? true
282
+ : undefined,
280
283
  },
281
284
  });
282
285
  }
@@ -426,6 +429,9 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
426
429
  workspaceItemId: item.workspaceItemId,
427
430
  publisher: item.hub?.publisher ?? 'community',
428
431
  baseSha256: item.sourceFiles[0]?.sha256,
432
+ localOriginUnrecognized: item.resolution === 'local_origin_unrecognized'
433
+ ? true
434
+ : undefined,
429
435
  },
430
436
  });
431
437
  }
@@ -613,6 +619,9 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
613
619
  workspaceItemId: hubPersonaItem.workspaceItemId,
614
620
  publisher: hubPersonaItem.hub?.publisher ?? 'community',
615
621
  baseSha256: hubPersonaItem.sourceFiles[0]?.sha256,
622
+ localOriginUnrecognized: hubPersonaItem.resolution === 'local_origin_unrecognized'
623
+ ? true
624
+ : undefined,
616
625
  },
617
626
  });
618
627
  }
@@ -686,6 +695,7 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
686
695
  || cloudWorkspaceUpdates.failed.length > 0
687
696
  || cloudRefreshChanges.downloaded.length > 0
688
697
  || (cloudChanges?.uploaded.length ?? 0) > 0
698
+ || (cloudChanges?.skipped.length ?? 0) > 0
689
699
  || cloudConflicts.length > 0
690
700
  || cloudFailures.length > 0
691
701
  ) ? {
@@ -693,6 +703,7 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
693
703
  workspace_update_failed: cloudWorkspaceUpdates.failed,
694
704
  downloaded: cloudRefreshChanges.downloaded,
695
705
  uploaded: cloudChanges?.uploaded ?? [],
706
+ skipped: cloudChanges?.skipped ?? [],
696
707
  conflicts: cloudConflicts,
697
708
  failed: cloudFailures,
698
709
  unchanged: cloudChanges?.unchanged ?? [],
@@ -79,7 +79,8 @@ export function listAgentWorkspaceBehaviorSources(
79
79
  if (!item) throw new Error(`agent_workspace_behavior_metadata_missing:${source.id}`);
80
80
  const trusted = item.sourceFiles[0]
81
81
  && item.resolution !== 'local_modified'
82
- && item.resolution !== 'concurrent_difference';
82
+ && item.resolution !== 'concurrent_difference'
83
+ && item.resolution !== 'local_origin_unrecognized';
83
84
  return {
84
85
  ...source,
85
86
  ...(trusted ? { trustedSourceSha256: item.sourceFiles[0]!.sha256 } : {}),
@@ -1,13 +1,23 @@
1
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
- import { dirname, join, resolve } from 'node:path';
1
+ import {
2
+ existsSync,
3
+ lstatSync,
4
+ mkdirSync,
5
+ readFileSync,
6
+ readdirSync,
7
+ renameSync,
8
+ writeFileSync,
9
+ } from 'node:fs';
10
+ import { dirname, join, relative, resolve } from 'node:path';
3
11
  import { randomUUID } from 'node:crypto';
4
12
  import type { AuthProfile } from './auth.js';
5
13
  import {
6
14
  resolveLocalAgentWorkspacePath,
15
+ type LocalAgentWorkspaceItem,
7
16
  type LocalAgentWorkspaceSnapshot,
8
17
  } from './agent-workspace-sync.js';
9
18
  import {
10
19
  capabilityWorkspacePath,
20
+ capabilityEntryForHubResource,
11
21
  readCapabilityWorkspaceRegistry,
12
22
  registerDiscoveredCapability,
13
23
  } from './capability-workspace.js';
@@ -21,17 +31,25 @@ import {
21
31
  linkAgentSkillTarget,
22
32
  overwriteAgentSkillTarget,
23
33
  readSkillName,
24
- resolveBundledClawclawSkill,
25
34
  unlinkAgentSkillTarget,
26
35
  type SkillHostMutationResult,
27
36
  } from './skill-host.js';
37
+ import { zipContentDigest } from './zip-store.js';
28
38
 
29
39
  interface ActiveSkillEntry {
30
40
  name: string;
31
- kind: 'official' | 'hub' | 'local';
41
+ kind: 'hub' | 'local';
32
42
  canonicalPath: string;
43
+ /** Last accepted remote directory hash. */
33
44
  sourceDigest?: string;
45
+ /** Latest observed remote directory hash. */
34
46
  remoteDigest?: string;
47
+ /** Upload-compatible digest for the last accepted remote content. */
48
+ sourceCloudDigest?: string;
49
+ /** Upload-compatible digest for the latest observed remote content. */
50
+ remoteCloudDigest?: string;
51
+ knownSourceDigests?: string[];
52
+ knownCloudDigests?: string[];
35
53
  resourceId?: string;
36
54
  versionId?: string;
37
55
  }
@@ -58,7 +76,12 @@ export interface AgentWorkspaceSkillDependencies {
58
76
  overwriteTarget?: (sourcePath: string, targetPath: string) => SkillHostMutationResult;
59
77
  linkTarget?: (sourcePath: string, targetPath: string) => SkillHostMutationResult;
60
78
  unlinkTarget?: (targetPath: string) => SkillHostMutationResult;
61
- bundledSkill?: () => string;
79
+ cloudDigest?: (path: string) => string | undefined;
80
+ }
81
+
82
+ export interface AccountSkillLinkSwitchResult {
83
+ removed: string[];
84
+ linked: string[];
62
85
  }
63
86
 
64
87
  function manifestPath(
@@ -98,6 +121,112 @@ function resultError(result: SkillHostMutationResult): string {
98
121
  return result.error ?? result.stderr?.trim() ?? 'skill host mutation failed';
99
122
  }
100
123
 
124
+ function skillCloudDigest(path: string): string | undefined {
125
+ if (!existsSync(path)) return undefined;
126
+ const root = resolve(path);
127
+ const files: Array<{ path: string; content: Buffer }> = [];
128
+ const visit = (directory: string): void => {
129
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
130
+ const child = join(directory, entry.name);
131
+ const stat = lstatSync(child);
132
+ if (stat.isSymbolicLink()) throw new Error('skill_source_symlink_unsupported');
133
+ if (stat.isDirectory()) visit(child);
134
+ else if (stat.isFile()) files.push({
135
+ path: relative(root, child).replaceAll('\\', '/'),
136
+ content: readFileSync(child),
137
+ });
138
+ }
139
+ };
140
+ try {
141
+ visit(root);
142
+ return files.length > 0 ? zipContentDigest(files) : undefined;
143
+ } catch {
144
+ return undefined;
145
+ }
146
+ }
147
+
148
+ function unique(values: Array<string | undefined>): string[] {
149
+ return [...new Set(values.filter((value): value is string => !!value))];
150
+ }
151
+
152
+ function accountManagedSkillSources(
153
+ workspaceDir: string,
154
+ profile: Pick<AuthProfile, 'apiKey'>,
155
+ ): Map<string, string> {
156
+ const skillsRoot = getUserDataAccountSkillsDir(workspaceDir, profile);
157
+ const sources = new Map<string, string>();
158
+ for (const [name] of Object.entries(readManifest(workspaceDir, profile).entries)) {
159
+ if (name === 'clawclaw') continue;
160
+ sources.set(name, join(skillsRoot, name));
161
+ }
162
+ for (const entry of Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)) {
163
+ if (
164
+ entry.type !== 'skill'
165
+ || entry.runtimeId === 'clawclaw'
166
+ || entry.origin !== 'local'
167
+ || entry.selection !== 'equipped'
168
+ ) continue;
169
+ sources.set(entry.runtimeId, capabilityWorkspacePath(workspaceDir, profile, entry));
170
+ }
171
+ return sources;
172
+ }
173
+
174
+ /**
175
+ * Move the device-wide account-managed Skill links before AuthStore commits an
176
+ * account switch. The package-owned clawclaw Skill is deliberately untouched.
177
+ */
178
+ export function switchActiveAccountSkillLinks(
179
+ workspaceDir: string,
180
+ previousProfile: Pick<AuthProfile, 'apiKey'> | null,
181
+ nextProfile: Pick<AuthProfile, 'apiKey'>,
182
+ dependencies: Pick<AgentWorkspaceSkillDependencies, 'targets' | 'linkTarget' | 'unlinkTarget'> = {},
183
+ ): AccountSkillLinkSwitchResult {
184
+ if (previousProfile?.apiKey === nextProfile.apiKey) return { removed: [], linked: [] };
185
+ const targets = dependencies.targets ?? agentSkillTargets;
186
+ const linkTarget = dependencies.linkTarget ?? linkAgentSkillTarget;
187
+ const unlinkTarget = dependencies.unlinkTarget ?? unlinkAgentSkillTarget;
188
+ const previous = previousProfile
189
+ ? accountManagedSkillSources(workspaceDir, previousProfile)
190
+ : new Map<string, string>();
191
+ const next = accountManagedSkillSources(workspaceDir, nextProfile);
192
+
193
+ for (const [name, source] of next) {
194
+ if (!existsSync(source) || readSkillName(source) !== name) {
195
+ throw new Error(`account_skill_source_unavailable:${name}`);
196
+ }
197
+ }
198
+
199
+ const removedTargets: Array<{ name: string; target: string }> = [];
200
+ const linkedTargets: Array<{ name: string; target: string }> = [];
201
+ try {
202
+ for (const [name] of previous) {
203
+ for (const target of targets(name)) {
204
+ const result = unlinkTarget(target);
205
+ if (!result.ok) throw new Error(`account_skill_unlink_failed:${name}:${resultError(result)}`);
206
+ removedTargets.push({ name, target });
207
+ }
208
+ }
209
+ for (const [name, source] of next) {
210
+ for (const target of targets(name)) {
211
+ const result = linkTarget(source, target);
212
+ if (!result.ok) throw new Error(`account_skill_link_failed:${name}:${resultError(result)}`);
213
+ linkedTargets.push({ name, target });
214
+ }
215
+ }
216
+ } catch (error) {
217
+ for (const { target } of linkedTargets.reverse()) unlinkTarget(target);
218
+ for (const { name, target } of removedTargets.reverse()) {
219
+ const source = previous.get(name);
220
+ if (source && existsSync(source)) linkTarget(source, target);
221
+ }
222
+ throw error;
223
+ }
224
+ return {
225
+ removed: [...previous.keys()],
226
+ linked: [...next.keys()],
227
+ };
228
+ }
229
+
101
230
  export function syncAgentWorkspaceSkills(
102
231
  workspaceDir: string,
103
232
  profile: Pick<AuthProfile, 'apiKey'>,
@@ -112,6 +241,7 @@ export function syncAgentWorkspaceSkills(
112
241
  const linkTarget = dependencies.linkTarget ?? linkAgentSkillTarget;
113
242
  const unlinkTarget = dependencies.unlinkTarget ?? unlinkAgentSkillTarget;
114
243
  const targets = dependencies.targets ?? agentSkillTargets;
244
+ const cloudDigest = dependencies.cloudDigest ?? skillCloudDigest;
115
245
  const skillsRoot = getUserDataAccountSkillsDir(workspaceDir, profile);
116
246
  mkdirSync(skillsRoot, { recursive: true });
117
247
 
@@ -121,10 +251,10 @@ export function syncAgentWorkspaceSkills(
121
251
  resourceId?: string;
122
252
  versionId?: string;
123
253
  remoteDigest?: string;
254
+ remoteCloudDigest?: string;
124
255
  publisher?: 'official' | 'self' | 'community';
256
+ remoteItem?: LocalAgentWorkspaceItem;
125
257
  }>();
126
- const bundled = (dependencies.bundledSkill ?? resolveBundledClawclawSkill)();
127
- desired.set('clawclaw', { kind: 'official', sourcePath: bundled });
128
258
 
129
259
  for (const item of snapshot.items.skill) {
130
260
  if (!item.skillRootPath) continue;
@@ -150,12 +280,22 @@ export function syncAgentWorkspaceSkills(
150
280
  resourceId: item.resourceId,
151
281
  versionId: item.versionId,
152
282
  remoteDigest: hashDirectory(path),
283
+ remoteCloudDigest: cloudDigest(path),
153
284
  publisher: item.hub?.publisher ?? 'community',
285
+ remoteItem: item,
154
286
  });
155
287
  }
156
288
 
157
289
  for (const entry of Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)) {
158
290
  if (entry.type !== 'skill' || entry.origin !== 'local' || entry.selection !== 'equipped') continue;
291
+ if (entry.runtimeId === 'clawclaw') {
292
+ failed.push({
293
+ name: entry.runtimeId,
294
+ action: 'add',
295
+ error: 'The official clawclaw Skill is managed by the installed CCL package',
296
+ });
297
+ continue;
298
+ }
159
299
  const path = capabilityWorkspacePath(workspaceDir, profile, entry);
160
300
  if (desired.has(entry.runtimeId)) {
161
301
  failed.push({ name: entry.runtimeId, action: 'add', error: 'local and Hub Skill names conflict' });
@@ -174,33 +314,69 @@ export function syncAgentWorkspaceSkills(
174
314
  const canonical = join(skillsRoot, name);
175
315
  const previous = current.entries[name];
176
316
  const sourceDigest = hashDirectory(item.sourcePath);
177
- if (!sourceDigest) {
317
+ const sourceCloudDigest = item.remoteCloudDigest ?? cloudDigest(item.sourcePath);
318
+ if (!sourceDigest || !sourceCloudDigest) {
178
319
  failed.push({ name, action: previous ? 'update' : 'add', error: 'Skill source is unreadable' });
179
320
  continue;
180
321
  }
181
322
  const canonicalDigest = hashDirectory(canonical);
323
+ const canonicalCloudDigest = cloudDigest(canonical);
324
+ const registered = item.kind === 'hub' && item.resourceId
325
+ ? capabilityEntryForHubResource(workspaceDir, profile, 'skill', item.resourceId)
326
+ : undefined;
327
+ const knownSourceDigests = unique([
328
+ ...(previous?.knownSourceDigests ?? []),
329
+ previous?.sourceDigest,
330
+ previous?.remoteDigest,
331
+ sourceDigest,
332
+ ]);
333
+ const knownCloudDigests = unique([
334
+ ...(previous?.knownCloudDigests ?? []),
335
+ previous?.sourceCloudDigest,
336
+ previous?.remoteCloudDigest,
337
+ registered?.hub?.baseSha256,
338
+ registered?.hub?.lastUploadedSha256,
339
+ sourceCloudDigest,
340
+ ]);
182
341
  let applied = false;
183
342
  let preserved = false;
343
+ let resolution: LocalAgentWorkspaceItem['resolution'] = 'hub';
184
344
  if (item.kind === 'local' && resolve(item.sourcePath) === resolve(canonical)) {
185
345
  applied = true;
186
- } else if (item.kind === 'official') {
187
- if (canonicalDigest !== sourceDigest) {
188
- const result = overwriteTarget(item.sourcePath, canonical);
189
- if (!result.ok) {
190
- failed.push({ name, action: previous ? 'update' : 'add', error: resultError(result) });
191
- continue;
192
- }
193
- applied = true;
194
- }
195
346
  } else if (canonicalDigest === sourceDigest) {
196
347
  applied = true;
197
- } else if (canonicalDigest === undefined || canonicalDigest === previous?.sourceDigest) {
348
+ } else if (canonicalDigest === undefined) {
198
349
  const result = overwriteTarget(item.sourcePath, canonical);
199
350
  if (!result.ok) {
200
351
  failed.push({ name, action: previous ? 'update' : 'add', error: resultError(result) });
201
352
  continue;
202
353
  }
203
354
  applied = true;
355
+ } else if (item.kind === 'hub') {
356
+ const originRecognized = registered?.hub?.localOriginUnrecognized !== true
357
+ && (!!registered?.hub || !!previous?.sourceDigest);
358
+ const localMatchesKnownVersion = knownSourceDigests.includes(canonicalDigest)
359
+ || (!!canonicalCloudDigest && knownCloudDigests.includes(canonicalCloudDigest));
360
+ const remoteAdvanced = registered?.hub
361
+ ? registered.hub.versionId !== item.versionId
362
+ : !!previous?.sourceDigest && previous.sourceDigest !== sourceDigest;
363
+ if (localMatchesKnownVersion) {
364
+ const result = overwriteTarget(item.sourcePath, canonical);
365
+ if (!result.ok) {
366
+ failed.push({ name, action: previous ? 'update' : 'add', error: resultError(result) });
367
+ continue;
368
+ }
369
+ applied = true;
370
+ resolution = 'known_online_old';
371
+ } else {
372
+ preserved = true;
373
+ resolution = !originRecognized
374
+ ? 'local_origin_unrecognized'
375
+ : remoteAdvanced
376
+ ? 'concurrent_difference'
377
+ : 'local_modified';
378
+ preservedModified.push(name);
379
+ }
204
380
  } else {
205
381
  preserved = true;
206
382
  preservedModified.push(name);
@@ -220,6 +396,28 @@ export function syncAgentWorkspaceSkills(
220
396
  }
221
397
  }
222
398
  if (linkFailed) continue;
399
+ const effectiveCloudDigest = cloudDigest(canonical);
400
+ if (!effectiveCloudDigest) {
401
+ failed.push({ name, action: previous ? 'update' : 'add', error: 'Canonical Skill is unreadable' });
402
+ continue;
403
+ }
404
+ if (item.remoteItem) {
405
+ item.remoteItem.resolution = resolution;
406
+ if (resolution === 'hub' || resolution === 'known_online_old') {
407
+ delete item.remoteItem.localContentDigest;
408
+ delete item.remoteItem.localModifiedAtMs;
409
+ } else {
410
+ item.remoteItem.localContentDigest = effectiveCloudDigest;
411
+ }
412
+ }
413
+ const acceptedVersionId = preserved
414
+ ? registered?.hub?.versionId ?? item.versionId
415
+ : item.versionId;
416
+ const acceptedCloudDigest = preserved
417
+ ? registered?.hub?.baseSha256
418
+ ?? previous?.sourceCloudDigest
419
+ ?? (registered?.hub?.versionId === item.versionId ? sourceCloudDigest : undefined)
420
+ : sourceCloudDigest;
223
421
  registerDiscoveredCapability(workspaceDir, profile, {
224
422
  type: 'skill',
225
423
  path: canonical,
@@ -230,9 +428,16 @@ export function syncAgentWorkspaceSkills(
230
428
  ...(item.kind === 'hub' && item.resourceId && item.versionId ? {
231
429
  hub: {
232
430
  resourceId: item.resourceId,
233
- versionId: item.versionId,
431
+ versionId: acceptedVersionId!,
432
+ workspaceItemId: item.remoteItem?.workspaceItemId,
234
433
  publisher: item.publisher ?? 'community',
235
- baseSha256: item.remoteDigest,
434
+ baseSha256: acceptedCloudDigest,
435
+ observedCloudVersionId: resolution === 'concurrent_difference'
436
+ ? item.versionId
437
+ : undefined,
438
+ localOriginUnrecognized: resolution === 'local_origin_unrecognized'
439
+ ? true
440
+ : undefined,
236
441
  },
237
442
  } : {}),
238
443
  });
@@ -240,8 +445,15 @@ export function syncAgentWorkspaceSkills(
240
445
  name,
241
446
  kind: item.kind,
242
447
  canonicalPath: canonical,
243
- sourceDigest: preserved ? previous?.sourceDigest : sourceDigest,
244
- remoteDigest: item.remoteDigest,
448
+ sourceDigest: preserved
449
+ ? previous?.sourceDigest
450
+ ?? (registered?.hub?.versionId === item.versionId ? sourceDigest : undefined)
451
+ : sourceDigest,
452
+ remoteDigest: sourceDigest,
453
+ sourceCloudDigest: acceptedCloudDigest,
454
+ remoteCloudDigest: sourceCloudDigest,
455
+ knownSourceDigests,
456
+ knownCloudDigests,
245
457
  resourceId: item.resourceId,
246
458
  versionId: item.versionId,
247
459
  };
@@ -251,7 +463,7 @@ export function syncAgentWorkspaceSkills(
251
463
  }
252
464
 
253
465
  for (const [name] of Object.entries(current.entries)) {
254
- if (desired.has(name)) continue;
466
+ if (name === 'clawclaw' || desired.has(name)) continue;
255
467
  let failedRemoval = false;
256
468
  for (const target of targets(name)) {
257
469
  const result = unlinkTarget(target);
@@ -72,7 +72,12 @@ export interface LocalAgentWorkspaceItem {
72
72
  contentDigest: string;
73
73
  sourceSha256: string;
74
74
  }>;
75
- resolution?: 'hub' | 'local_modified' | 'concurrent_difference' | 'known_online_old';
75
+ resolution?:
76
+ | 'hub'
77
+ | 'local_modified'
78
+ | 'concurrent_difference'
79
+ | 'known_online_old'
80
+ | 'local_origin_unrecognized';
76
81
  localContentDigest?: string;
77
82
  localModifiedAtMs?: number;
78
83
  }
@@ -398,6 +403,7 @@ interface LocalOverride {
398
403
  sha256: string;
399
404
  contentDigest: string;
400
405
  modifiedAtMs: number;
406
+ originRecognized: boolean;
401
407
  }
402
408
 
403
409
  interface WorkingCopyMetadata {
@@ -600,7 +606,9 @@ function inspectLocalSnapshot(
600
606
  }
601
607
  const localDigest = singleFileContentDigest(source.relativePath, bytes);
602
608
  const modifiedAtMs = statSync(workingPath).mtimeMs;
603
- item.resolution = 'local_modified';
609
+ item.resolution = item.resolution === 'local_origin_unrecognized'
610
+ ? 'local_origin_unrecognized'
611
+ : 'local_modified';
604
612
  item.localContentDigest = localDigest;
605
613
  item.localModifiedAtMs = modifiedAtMs;
606
614
  if (projectionSha !== localSha) projectionOutdated = true;
@@ -609,6 +617,7 @@ function inspectLocalSnapshot(
609
617
  sha256: localSha,
610
618
  contentDigest: localDigest,
611
619
  modifiedAtMs,
620
+ originRecognized: item.resolution !== 'local_origin_unrecognized',
612
621
  });
613
622
  }
614
623
  }
@@ -753,6 +762,7 @@ export async function syncAgentWorkspaceConfig(
753
762
  bytes,
754
763
  ),
755
764
  modifiedAtMs: statSync(workingPath).mtimeMs,
765
+ originRecognized: persistedWorkingMetadata !== undefined,
756
766
  };
757
767
  }
758
768
  }
@@ -774,9 +784,11 @@ export async function syncAgentWorkspaceConfig(
774
784
  && !persistedWorkingMetadata.knownVersions.some(
775
785
  (entry) => entry.versionId === materialized.versionId,
776
786
  );
777
- materialized.resolution = remoteAdvancedFromLocalBaseline
778
- ? 'concurrent_difference'
779
- : 'local_modified';
787
+ materialized.resolution = !override.originRecognized
788
+ ? 'local_origin_unrecognized'
789
+ : remoteAdvancedFromLocalBaseline
790
+ ? 'concurrent_difference'
791
+ : 'local_modified';
780
792
  materialized.localContentDigest = override.contentDigest;
781
793
  materialized.localModifiedAtMs = override.modifiedAtMs;
782
794
  } else {
@@ -242,9 +242,17 @@ export async function refreshCapabilitiesFromCloud(
242
242
  }
243
243
  const detail = await client.getResource(type, hub.resourceId, workspaceItemId);
244
244
  if (detail.versionId === hub.versionId) {
245
- if (hub.observedCloudVersionId) updateCapabilityHubIdentity(workspaceDir, profile, entry.key, {
245
+ if (
246
+ hub.observedCloudVersionId
247
+ || (hub.localOriginUnrecognized && (
248
+ before === hub.baseSha256 || before === hub.lastUploadedSha256
249
+ ))
250
+ ) updateCapabilityHubIdentity(workspaceDir, profile, entry.key, {
246
251
  ...hub,
247
252
  observedCloudVersionId: undefined,
253
+ localOriginUnrecognized: before === hub.baseSha256 || before === hub.lastUploadedSha256
254
+ ? undefined
255
+ : hub.localOriginUnrecognized,
248
256
  });
249
257
  result.unchanged.push({ type: entry.type, id: entry.runtimeId });
250
258
  continue;
@@ -289,6 +297,7 @@ export async function refreshCapabilitiesFromCloud(
289
297
  baseSha256: artifact.digest,
290
298
  lastUploadedSha256: artifact.digest,
291
299
  observedCloudVersionId: undefined,
300
+ localOriginUnrecognized: undefined,
292
301
  });
293
302
  result.downloaded.push({
294
303
  type: entry.type,
@@ -1,9 +1,11 @@
1
1
  import {
2
+ existsSync,
2
3
  lstatSync,
3
4
  readFileSync,
5
+ realpathSync,
4
6
  readdirSync,
5
7
  } from 'node:fs';
6
- import { basename, extname, join, relative } from 'node:path';
8
+ import { basename, dirname, extname, join, relative } from 'node:path';
7
9
  import { createHash } from 'node:crypto';
8
10
  import type { AuthProfile } from './auth.js';
9
11
  import {
@@ -21,7 +23,14 @@ import {
21
23
  type ResourceType,
22
24
  } from './hub-client.js';
23
25
  import type { LocalAgentWorkspaceSnapshot } from './agent-workspace-sync.js';
26
+ import { readSkillName } from './skill-host.js';
24
27
  import { createStoredZip, zipContentDigest, type ZipStoreEntry } from './zip-store.js';
28
+ import {
29
+ inspectClawclawBehaviorSource,
30
+ } from '../runtime/clawclaw/plugins/behavior/behavior-source.js';
31
+ import {
32
+ listClawclawPerceptionSourcesInDirectory,
33
+ } from '../runtime/clawclaw/plugins/perception/perception-source.js';
25
34
 
26
35
  export interface CapabilityCloudSyncChange {
27
36
  type: CapabilityWorkspaceType;
@@ -46,10 +55,17 @@ export interface CapabilityCloudSyncFailure {
46
55
  error: string;
47
56
  }
48
57
 
58
+ export interface CapabilityCloudSyncSkip {
59
+ type: CapabilityWorkspaceType;
60
+ id: string;
61
+ reason: 'local_origin_unrecognized';
62
+ }
63
+
49
64
  export interface CapabilityCloudSyncResult {
50
65
  uploaded: CapabilityCloudSyncChange[];
51
66
  conflicts: CapabilityCloudSyncConflict[];
52
67
  failed: CapabilityCloudSyncFailure[];
68
+ skipped: CapabilityCloudSyncSkip[];
53
69
  unchanged: Array<{ type: CapabilityWorkspaceType; id: string }>;
54
70
  }
55
71
 
@@ -138,6 +154,44 @@ function snapshotResolution(
138
154
  .find((item) => item.resourceId === resourceId)?.resolution;
139
155
  }
140
156
 
157
+ const MAX_CAPABILITY_UPLOAD_BYTES = 10 * 1024 * 1024;
158
+
159
+ function validateUploadPayload(
160
+ entry: CapabilityWorkspaceEntry,
161
+ path: string,
162
+ payload: ReturnType<typeof uploadPayload>,
163
+ ): void {
164
+ const totalBytes = payload.source.reduce((total, file) => total + file.bytes.length, 0);
165
+ if (totalBytes > MAX_CAPABILITY_UPLOAD_BYTES) {
166
+ throw new Error('capability_validation_failed:content_too_large');
167
+ }
168
+ if (entry.type === 'behavior') {
169
+ const source = inspectClawclawBehaviorSource(path, dirname(path));
170
+ if (!source || source.id !== entry.runtimeId) {
171
+ throw new Error('capability_validation_failed:behavior_invalid');
172
+ }
173
+ return;
174
+ }
175
+ if (entry.type === 'perception') {
176
+ const resolvedPath = realpathSync(path);
177
+ const source = listClawclawPerceptionSourcesInDirectory(dirname(path))
178
+ .find((candidate) => realpathSync(candidate.sourcePath) === resolvedPath);
179
+ if (!source || source.id !== entry.runtimeId) {
180
+ throw new Error('capability_validation_failed:perception_invalid');
181
+ }
182
+ return;
183
+ }
184
+ if (entry.type === 'persona') {
185
+ if (!existsSync(path) || extname(path).toLowerCase() !== '.md') {
186
+ throw new Error('capability_validation_failed:persona_invalid');
187
+ }
188
+ return;
189
+ }
190
+ if (readSkillName(path) !== entry.runtimeId) {
191
+ throw new Error('capability_validation_failed:skill_invalid');
192
+ }
193
+ }
194
+
141
195
  export async function syncCapabilitiesToCloud(
142
196
  workspaceDir: string,
143
197
  profile: Pick<AuthProfile, 'apiKey' | 'serverUrl'>,
@@ -149,6 +203,7 @@ export async function syncCapabilitiesToCloud(
149
203
  uploaded: [],
150
204
  conflicts: [],
151
205
  failed: [],
206
+ skipped: [],
152
207
  unchanged: [],
153
208
  };
154
209
  const selectedKeys = dependencies.entryKeys ? new Set(dependencies.entryKeys) : undefined;
@@ -188,6 +243,20 @@ export async function syncCapabilitiesToCloud(
188
243
  });
189
244
  continue;
190
245
  }
246
+ if (
247
+ (
248
+ entry.hub?.localOriginUnrecognized
249
+ || (entry.hub && snapshotResolution(snapshot, entry.hub.resourceId) === 'local_origin_unrecognized')
250
+ )
251
+ && entry.conflictChoice !== 'local'
252
+ ) {
253
+ result.skipped.push({
254
+ type: entry.type,
255
+ id: entry.runtimeId,
256
+ reason: 'local_origin_unrecognized',
257
+ });
258
+ continue;
259
+ }
191
260
  if (
192
261
  entry.hub?.observedCloudVersionId
193
262
  && entry.hub.observedCloudVersionId !== entry.hub.versionId
@@ -234,6 +303,7 @@ export async function syncCapabilitiesToCloud(
234
303
  }
235
304
  baseVersionId = latest.versionId;
236
305
  }
306
+ validateUploadPayload(entry, path, payload);
237
307
  const uploadedSource = await client.uploadFiles(sourceFileType(entry.type), payload.source);
238
308
  let packageFileId: string | undefined;
239
309
  if (payload.packageUpload) {
@@ -29,6 +29,8 @@ export interface CapabilityHubIdentity {
29
29
  lastUploadedSha256?: string;
30
30
  pendingBackpackRestoreResourceId?: string;
31
31
  observedCloudVersionId?: string;
32
+ /** The working copy existed before CCL had a trustworthy Hub baseline. */
33
+ localOriginUnrecognized?: boolean;
32
34
  }
33
35
 
34
36
  export interface CapabilityWorkspaceEntry {
@@ -13,6 +13,7 @@ import {
13
13
  } from '../runtime/ws-client.js';
14
14
  import { RuntimeLogger } from '../runtime/runtime-logger.js';
15
15
  import type { RawWsMessageSink } from '../runtime/raw-ws-log.js';
16
+ import type { GameSyncPerceptionReport } from '../runtime/game-sync-protocol.js';
16
17
  import type { QueueMode } from './competition.js';
17
18
  import type {
18
19
  CreateRoomOptions,
@@ -514,6 +515,15 @@ export class GameClient {
514
515
  this.rememberGameSyncResumeState(this.ws?.resumeState);
515
516
  }
516
517
 
518
+ /** Send display-only perception output over the active GameSync connection. */
519
+ reportGameSyncPerceptions(perceptions: readonly GameSyncPerceptionReport[]): boolean {
520
+ return this.ws?.reportPerceptions(perceptions) ?? false;
521
+ }
522
+
523
+ get gameSyncLocale(): 'zh-CN' | 'en-US' {
524
+ return this.ws?.resumeState?.locale ?? this.gameSyncResumeState?.locale ?? 'zh-CN';
525
+ }
526
+
517
527
  /**
518
528
  * Try to discover game server from /queue/status.
519
529
  * If found and WS is enabled, reconnects WS to the game server.
@@ -76,6 +76,7 @@ import {
76
76
  ClaudeChannelMailboxAdapter,
77
77
  ClaudeChannelSocketSink,
78
78
  DesktopEventSocketSink,
79
+ GameSyncPerceptionReportAdapter,
79
80
  AgentMailboxCoordinator,
80
81
  clawclawEventRequiresDetails,
81
82
  MailboxEventBatchPump,
@@ -898,7 +899,20 @@ export async function runClawclawOwner(
898
899
  monitorEnabled: !!options.notificationHost,
899
900
  diagnostic: (name, attributes, severity) => runtime?.diagnostic(name, attributes, severity),
900
901
  });
901
- const mailboxDrivers: ClawclawMailboxDriver[] = [mailboxService, cclEventsMailbox];
902
+ const perceptionReportAdapter = new GameSyncPerceptionReportAdapter({
903
+ producerPluginId: assembly.perception.id,
904
+ descriptor: (eventType) => assembly.perception.localizedModuleDescriptorForEvent(
905
+ eventType,
906
+ client.gameSyncLocale,
907
+ ),
908
+ send: (reports) => client.reportGameSyncPerceptions(reports),
909
+ diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes),
910
+ });
911
+ const mailboxDrivers: ClawclawMailboxDriver[] = [
912
+ mailboxService,
913
+ cclEventsMailbox,
914
+ perceptionReportAdapter,
915
+ ];
902
916
  if (options.desktopEvents) {
903
917
  desktopMailbox = new AgentMailboxCoordinator({
904
918
  repository: mailboxRepository,
@@ -0,0 +1,107 @@
1
+ import { createHash } from 'node:crypto';
2
+ import type { GameSyncPerceptionReport } from '../../../../game-sync-protocol.js';
3
+ import type { CanonicalEvent } from '../../../../framework/events/index.js';
4
+ import type {
5
+ ClawclawMailboxAdapterDescriptor,
6
+ ClawclawMailboxDriver,
7
+ } from '../mailbox-plugin.js';
8
+
9
+ const GAME_SYNC_PERCEPTION_REPORT_BATCH_SIZE = 20;
10
+ const PERCEPTION_REPORT_UUID_NAMESPACE = Buffer.from(
11
+ '3c45fc594dd54a59a22185085c1096d1',
12
+ 'hex',
13
+ );
14
+
15
+ export interface GameSyncPerceptionDescriptor {
16
+ readonly perceptionId: string;
17
+ readonly name: string;
18
+ }
19
+
20
+ export interface GameSyncPerceptionReportAdapterOptions {
21
+ readonly send: (reports: readonly GameSyncPerceptionReport[]) => boolean;
22
+ readonly descriptor: (eventType: string) => GameSyncPerceptionDescriptor | undefined;
23
+ readonly producerPluginId: string;
24
+ readonly diagnostic?: (
25
+ name: string,
26
+ attributes?: Readonly<Record<string, unknown>>,
27
+ ) => void;
28
+ }
29
+
30
+ function uuidForEvent(event: CanonicalEvent): string {
31
+ const bytes = createHash('sha1')
32
+ .update(PERCEPTION_REPORT_UUID_NAMESPACE)
33
+ .update(event.sessionId)
34
+ .update('\0')
35
+ .update(event.eventId)
36
+ .digest()
37
+ .subarray(0, 16);
38
+ bytes[6] = (bytes[6]! & 0x0f) | 0x50;
39
+ bytes[8] = (bytes[8]! & 0x3f) | 0x80;
40
+ const hex = bytes.toString('hex');
41
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
42
+ }
43
+
44
+ function sourceTick(event: CanonicalEvent): number | undefined {
45
+ for (const candidate of [event.payload.to_tick, event.payload.source_tick, event.payload.tick]) {
46
+ if (Number.isSafeInteger(candidate) && Number(candidate) >= 0) return Number(candidate);
47
+ }
48
+ return undefined;
49
+ }
50
+
51
+ /** Best-effort Mailbox fan-out to the active GameSync connection. */
52
+ export class GameSyncPerceptionReportAdapter implements ClawclawMailboxDriver {
53
+ readonly adapter: ClawclawMailboxAdapterDescriptor = {
54
+ id: 'clawclaw.mailbox.adapter.game-sync-perception-report',
55
+ acknowledgement: 'none',
56
+ };
57
+
58
+ private stopped = false;
59
+
60
+ constructor(private readonly options: GameSyncPerceptionReportAdapterOptions) {}
61
+
62
+ observeEvents(events: readonly CanonicalEvent[]): void {
63
+ if (this.stopped) return;
64
+ let skipped = 0;
65
+ const reports: GameSyncPerceptionReport[] = [];
66
+ for (const event of events) {
67
+ if (
68
+ event.producerPluginId !== this.options.producerPluginId
69
+ || event.deliveryClass === 'internal_only'
70
+ ) continue;
71
+ const descriptor = this.options.descriptor(event.type);
72
+ const output = typeof event.payload.text === 'string' ? event.payload.text.trim() : '';
73
+ const tick = sourceTick(event);
74
+ if (!descriptor || !descriptor.name.trim() || !output || tick === undefined) {
75
+ skipped += 1;
76
+ continue;
77
+ }
78
+ reports.push({
79
+ id: uuidForEvent(event),
80
+ name: descriptor.name.trim(),
81
+ output,
82
+ source_tick: tick,
83
+ });
84
+ }
85
+ if (skipped > 0) {
86
+ this.options.diagnostic?.('runtime.mailbox.perception_report_skipped', {
87
+ event_count: skipped,
88
+ error_code: 'PERCEPTION_REPORT_FIELDS_MISSING',
89
+ });
90
+ }
91
+ for (let index = 0; index < reports.length; index += GAME_SYNC_PERCEPTION_REPORT_BATCH_SIZE) {
92
+ const batch = reports.slice(index, index + GAME_SYNC_PERCEPTION_REPORT_BATCH_SIZE);
93
+ if (!this.options.send(batch)) {
94
+ this.options.diagnostic?.('runtime.mailbox.perception_report_dropped', {
95
+ event_count: batch.length,
96
+ error_code: 'GAME_SYNC_NOT_CONNECTED',
97
+ });
98
+ }
99
+ }
100
+ }
101
+
102
+ async flush(): Promise<void> {}
103
+
104
+ async stop(): Promise<void> {
105
+ this.stopped = true;
106
+ }
107
+ }
@@ -1,6 +1,7 @@
1
1
  export * from './agent-mailbox-coordinator.js';
2
2
  export * from './adapters/claude-channel-adapter.js';
3
3
  export * from './adapters/claude-channel-socket.js';
4
+ export * from './adapters/game-sync-perception-report-adapter.js';
4
5
  export * from './consumer-ids.js';
5
6
  export * from './desktop-event-socket.js';
6
7
  export * from './mailbox-event-batch-delivery.js';
@@ -821,6 +821,18 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
821
821
  return this.modules.map(({ manifest }) => resolveClawclawResourceMetadata(manifest, locale));
822
822
  }
823
823
 
824
+ localizedModuleDescriptorForEvent(
825
+ type: string,
826
+ locale: string,
827
+ ): (ClawclawResolvedResourceMetadata & { perceptionId: string }) | undefined {
828
+ const module = this.modules.find(({ manifest }) => manifest.produces.includes(type));
829
+ if (!module) return undefined;
830
+ return {
831
+ ...resolveClawclawResourceMetadata(module.manifest, locale),
832
+ perceptionId: module.manifest.id,
833
+ };
834
+ }
835
+
824
836
  localizedEventDescriptors(locale: string): LocalizedPerceptionEventDescriptor[] {
825
837
  return this.modules.flatMap(({ manifest }) => manifest.produces.flatMap((type) => {
826
838
  const metadata = manifest.eventMetadata?.[type];
@@ -31,6 +31,20 @@ export interface GameSyncErrorData {
31
31
  readonly message?: string;
32
32
  }
33
33
 
34
+ export interface GameSyncPerceptionReport {
35
+ readonly id: string;
36
+ readonly name: string;
37
+ readonly output: string;
38
+ readonly source_tick: number;
39
+ }
40
+
41
+ export interface GameSyncPerceptionReportMessage {
42
+ readonly type: 'game.sync.perception.report';
43
+ readonly data: {
44
+ readonly perceptions: readonly GameSyncPerceptionReport[];
45
+ };
46
+ }
47
+
34
48
  export type GameSyncServerMessage =
35
49
  | { readonly type: 'game.sync.snapshot'; readonly data: GameSyncSnapshotData }
36
50
  | { readonly type: 'game.sync.update'; readonly data: GameSyncUpdateData }
@@ -71,6 +85,39 @@ function eventArray(value: unknown, field: string): Record<string, any>[] {
71
85
  });
72
86
  }
73
87
 
88
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
89
+
90
+ /** Build one client perception report frame using the backend's all-or-nothing validation rules. */
91
+ export function gameSyncPerceptionReportMessage(
92
+ perceptions: readonly GameSyncPerceptionReport[],
93
+ ): GameSyncPerceptionReportMessage {
94
+ if (perceptions.length < 1 || perceptions.length > 20) {
95
+ throw new TypeError('GameSync perception report must contain between 1 and 20 items');
96
+ }
97
+ const ids = new Set<string>();
98
+ const detached = perceptions.map((perception, index) => {
99
+ if (!UUID_PATTERN.test(perception.id)) {
100
+ throw new TypeError(`GameSync perception report[${index}].id must be a UUID`);
101
+ }
102
+ if (ids.has(perception.id)) {
103
+ throw new TypeError('GameSync perception report IDs must be unique within a batch');
104
+ }
105
+ ids.add(perception.id);
106
+ if (typeof perception.name !== 'string' || perception.name.length === 0) {
107
+ throw new TypeError(`GameSync perception report[${index}].name must be a non-empty string`);
108
+ }
109
+ if (typeof perception.output !== 'string') {
110
+ throw new TypeError(`GameSync perception report[${index}].output must be a string`);
111
+ }
112
+ integer(perception.source_tick, `GameSync perception report[${index}].source_tick`);
113
+ return { ...perception };
114
+ });
115
+ return {
116
+ type: 'game.sync.perception.report',
117
+ data: { perceptions: detached },
118
+ };
119
+ }
120
+
74
121
  /** Validate only the envelope and sequencing fields CCL must trust. */
75
122
  export function parseGameSyncMessage(value: unknown): GameSyncServerMessage {
76
123
  const envelope = record(value, 'GameSync message');
@@ -7,9 +7,11 @@ import { WsConnectionState } from '../sdk/types.js';
7
7
  import type { RawWsMessageSink } from './raw-ws-log.js';
8
8
  import {
9
9
  applyGameSyncDelta,
10
+ gameSyncPerceptionReportMessage,
10
11
  gameSyncUrl,
11
12
  parseGameSyncMessage,
12
13
  type GameSyncErrorData,
14
+ type GameSyncPerceptionReport,
13
15
  } from './game-sync-protocol.js';
14
16
 
15
17
  export interface GameSyncResumeState {
@@ -163,6 +165,11 @@ export class WsClient {
163
165
  return this.committedBaseline ? structuredClone(this.committedBaseline) : undefined;
164
166
  }
165
167
 
168
+ /** Best-effort perception output; the server intentionally sends no acknowledgement. */
169
+ reportPerceptions(perceptions: readonly GameSyncPerceptionReport[]): boolean {
170
+ return this.send(gameSyncPerceptionReportMessage(perceptions));
171
+ }
172
+
166
173
  /**
167
174
  * Advance the resume/ACK watermark only after Source has durably accepted the
168
175
  * matching frame. Reading a socket frame is not sufficient authority.