@myclaw163/clawclaw-cli 0.10.6 → 0.10.8

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.
Files changed (68) hide show
  1. package/dist/strategy-worker/assets/clawclaw-spatial-facts.json +1383 -0
  2. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-3VLVCU6P.js +71 -0
  3. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-ATQQZA4X.js +44 -0
  4. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-CF6IEQ4V.js +12 -0
  5. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-JMX6D6A3.js +260 -0
  6. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-QEPKDSLE.js +278 -0
  7. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-ZQILO6OM.js +0 -0
  8. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/clawclaw-walkable.bin +0 -0
  9. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/host.js +1389 -0
  10. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-behavior-plugin.js +22 -0
  11. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-module-input.js +0 -0
  12. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-perception-plugin.js +72 -0
  13. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-sdk.js +3108 -0
  14. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-strategy-plugin.js +25 -0
  15. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-trigger-plugin.js +16 -0
  16. package/docs/custom-modules/api-reference.md +10 -8
  17. package/docs/custom-modules/perception.md +26 -3
  18. package/docs/desktop-event-push.md +2 -1
  19. package/docs/runtime/behavior-runtime.md +3 -1
  20. package/docs/runtime/official-perception-modules.md +2 -2
  21. package/docs/user-guide/behavior.md +3 -1
  22. package/docs/user-guide/desktop-auth.md +33 -1
  23. package/package.json +5 -3
  24. package/scripts/build-strategy-worker.mjs +28 -0
  25. package/scripts/migrate-official-perceptions.mjs +157 -0
  26. package/skills/clawclaw/SKILL.md +3 -3
  27. package/skills/clawclaw/references/BEHAVIORS.md +2 -0
  28. package/skills/clawclaw/references/TACTICS.md +4 -0
  29. package/skills/clawclaw-creator/SKILL.md +3 -1
  30. package/skills/clawclaw-creator/references/CUSTOM-MODULE-API.md +10 -8
  31. package/skills/clawclaw-creator/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +26 -3
  32. package/skills/clawclaw-creator/references/CUSTOM-SKILL-DEVELOPMENT.md +1 -1
  33. package/src/commands/capability.ts +4 -2
  34. package/src/commands/load.ts +5 -2
  35. package/src/lib/agent-workspace-skills.ts +12 -7
  36. package/src/lib/capability-cloud-sync.ts +13 -7
  37. package/src/lib/capability-discovery.ts +10 -3
  38. package/src/lib/capability-selection.ts +7 -0
  39. package/src/lib/game-client.ts +33 -6
  40. package/src/lib/lobby-host-context.ts +74 -0
  41. package/src/lib/package-skills.ts +11 -1
  42. package/src/lib/participation-status.ts +5 -0
  43. package/src/pipeline/event-format.ts +2 -0
  44. package/src/pipeline/event-hints.ts +1 -0
  45. package/src/runtime/clawclaw/behavior-start-control.ts +114 -0
  46. package/src/runtime/clawclaw/notification-policy.ts +1 -0
  47. package/src/runtime/clawclaw/owner.ts +21 -4
  48. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +1 -0
  49. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +11 -6
  50. package/src/runtime/clawclaw/plugins/behavior/behavior-module-loader.ts +48 -1
  51. package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +2 -0
  52. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +28 -6
  53. package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +25 -3
  54. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +1 -1
  55. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +9 -0
  56. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +3 -0
  57. package/src/runtime/clawclaw/plugins/perception/module-input-boundary.ts +64 -0
  58. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +37 -49
  59. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +3 -1
  60. package/src/runtime/clawclaw/plugins/source/room-transport.ts +46 -9
  61. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +18 -4
  62. package/src/runtime/clawclaw/plugins/source/types.ts +2 -0
  63. package/src/runtime/clawclaw/plugins/system-perception/sabotage-availability-rule.ts +2 -0
  64. package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +122 -61
  65. package/src/runtime/clawclaw-event-catalog.ts +1 -0
  66. package/src/sdk/perception-plugin/index.ts +1 -0
  67. package/src/sdk/perception-plugin/lifecycle.ts +15 -0
  68. package/src/sdk/perception-plugin/module.ts +15 -0
@@ -6,7 +6,7 @@
6
6
 
7
7
  CCL 强制启用七类内置感知:玩家、任务、能力、紧急任务、房间与流程、会议、策略消息。内置代码随 CCL 发布,暂不允许用户修改、关闭或配置。Hub 上的官方资源和社区脚本属于可装配的自定义感知,不会替换这些内置模块。
8
8
 
9
- 所有感知独立读取本轮输入,互不消费对方输出;多个脚本可并行计算,各自按轮次保存检查点。自定义感知只能订阅 Source/后端原始事件,不能订阅 players_changed、tasks_changed、ability.*、meeting_state 等旧系统派生输出。用 gameState/frame 判断这些条件,任务差异可直接用每个模块独立的 taskChanges。
9
+ 内置与自定义感知使用同一个 `evaluate(input, api)`、输入类型和结果类型,由注册方决定是否强制启用及能否转发原事实。所有感知独立读取本轮输入,互不消费对方输出;多个脚本可并行计算,各自按轮次保存检查点。自定义感知只能订阅 Source/后端原始事件,不能订阅 players_changed、tasks_changed、ability.*、meeting_state 等旧系统派生输出。用 gameState/frame 判断这些条件,任务差异可直接用每个模块独立的 taskChanges。
10
10
 
11
11
  策略产生的公开事件先记录,由内置策略消息感知在后续轮次转发;内容、类型、发生时间保留。在感知模块中,只有该内置模块能读取策略事件。退出、断线等固定生命周期消息由系统通道交付。自定义感知的 wakeAgent 只影响自己的通知,不能覆盖内置或其他模块。
12
12
 
@@ -61,14 +61,37 @@ export default class FirstSighting extends ClawclawPerception {
61
61
  | gameState / frame | 当前玩家权威 State、可见观察帧;缺失时为 null,不代表事实不存在 |
62
62
  | events | 声明订阅的 Source/后端原始事实,不包含其他感知或策略的输出 |
63
63
  | taskChanges | 各模块独立比较连续权威任务快照得到的变化;对应同轮输入,不订阅内置或其他感知 |
64
+ | lifecycle | 本轮新增的阶段切换、初始化、恢复、观察中断、死亡、结束和查询边界 |
65
+ | roomState / queueState | 房间、匹配队列快照,缺失时为 null |
66
+ | source / eventStates | 输入帧来源,以及每条订阅事实接受时对应的 State |
64
67
  | scope / nowMs / boundary | 当前作用域、观测时间,以及 initial/recovery 边界 |
65
68
  | config / state | Manifest 参数与上一轮提交后的私有检查点 |
66
69
  | availableStrategies | 当前可加载的策略操作名 |
67
70
 
68
- 结果可同时包含 `state`、`events` 和可选 `activations`,也可以只返回其中需要的部分。每次计算使用新实例,跨回调记忆用返回的 state,不能依赖实例字段。阶段、对局或有效状态边界会清理相应记忆;恢复使用检查点,不重放旧通知来触发动作。
71
+ 结果可同时包含 `state`、`events` 和可选 `activations`,也可以只返回其中需要的部分。每次计算使用新实例,跨回调记忆用返回的 state,不能依赖实例字段。宿主只在更换对局/作用域时清空私有状态,不在进出会议时统一清空。阶段切换通过 lifecycle 传入,由脚本按需收尾观察片段、刷新部分字段并返回下一份 state。连接恢复保留检查点并显式标记 recovery,不伪造进入/离开会议,也不应重放旧通知。
69
72
 
70
73
  Manifest 使用 `apiVersion: 3`、`id`、`description`,可声明 `consumes`、`produces`、`inputs`、`config` 、可选固定 `strategies` 绑定与本地化信息。不填写 kind。事件必须在 produces 中声明,并使用稳定的 key 和可序列化 payload;text 可用于直接表达通知。不能冒充击杀、能力就绪或策略生命周期等系统事实。
71
74
 
75
+ ## 按需处理进入或离开会议
76
+
77
+ `enteredPhase(input, 'meeting')` 和 `leftPhase(input, 'meeting')` 只匹配真实的阶段转换。首次加载时已经在会议中、断线后在会议中恢复,都不会假报进入会议;分别检查 `hasPerceptionBoundary(input, 'initial')` / `'recovery'`。
78
+
79
+ ```ts
80
+ import { enteredPhase, leftPhase, resetPerceptionState }
81
+ from '@myclaw163/clawclaw-cli/perception-plugin';
82
+
83
+ // 在 evaluate 中:先用旧状态收尾需要报告的片段,再只清理临时观察。
84
+ let state = (input.state ?? { seen: [], pending: [] }) as {
85
+ seen: string[]; pending: string[];
86
+ };
87
+ if (enteredPhase(input, 'meeting') || leftPhase(input, 'meeting')) {
88
+ state = resetPerceptionState(state, { pending: [] });
89
+ }
90
+ return { state }; // seen 保留;共享 api.memory 不会被这个工具修改。
91
+ ```
92
+
93
+ `lifecycle` 是本轮输入提示,不会自动通知 Agent。需要通知时仍由感知返回自己的 events;收尾旧片段可指定合法 ISO 时间 `occurredAt`,避免把旧观察标成当前发生。`forwards` 仅供具有注册权限的内置模块转发原事实,自定义脚本不能通过 Manifest 获得该权限。
94
+
72
95
  ## 通知内容与过滤
73
96
 
74
97
  感知生成通知时确定并保存正文、结构化信息和提示。自定义感知可在 payload 中提供字符串 hint;非字符串 hint 以及旧 next_step/notice 字段由感知执行器过滤。内置感知会先去掉后端或策略原始事件的这些提示字段,再根据自己的固定规则生成提示。原始事件保留用于核查,不因通知过滤而修改。
@@ -115,7 +138,7 @@ ccl strategy watch community.auto-escape
115
138
 
116
139
  `perception update` 更新判断参数,不清除 state 或 api.memory;`strategy update` 更新执行参数,不要求 watch。配套感知和策略装配完成且绑定可用时,自动反射默认开启。`watch/unwatch` 用于局中恢复/关闭所有明确绑定它的感知的自动激活;**unwatch 不停止感知观察和通知,也不禁止它读写记忆**,只撤销关联 Reflex 并拦截后续请求。参数与开关本局有效,换局重置。`availableBindings`/`availableStrategies` 表示可用依赖;`enabledBindings` 进一步表示允许自动激活的绑定,感知可据此避免把关闭期间的命中当成已经执行。
117
140
 
118
- `evaluate(input, api)` 的第二个参数提供 `api.memory.get/set/delete`。感知所有绑定都解析到同一个可用策略时,与其共享持续记忆;否则使用模块私有记忆。关闭自动反射、改参和 Worker 重建保留;换局、game_over、Owner 退出清空。input.state 则是每次结果返回的检查点,可在阶段边界清理。不要依赖实例字段或模块全局变量。
141
+ `evaluate(input, api)` 的第二个参数提供只读地图查询 `api.spatial` 与 `api.memory.get/set/delete`。感知所有绑定都解析到同一个可用策略时,与其共享持续记忆;否则使用模块私有记忆。关闭自动反射、改参和 Worker 重建保留;换局、game_over、Owner 退出清空。input.state 则是每次结果返回的检查点;阶段变化不自动清理,脚本可以只刷新连续观察字段,保留跨会议知识。不要依赖实例字段或模块全局变量。
119
142
 
120
143
  ## 编写规则
121
144
 
@@ -37,7 +37,7 @@ description: Organize visible meeting evidence before speaking.
37
37
  不要推断不可见身份,不要把动作请求当作执行成功。
38
38
  ```
39
39
 
40
- 目录名与 `name` 保持一致。使用唯一名称;名称以字母或数字开头,后续只使用字母、数字、点、下划线或连字符,总长度不超过 128 字符。不要占用官方技能名称 `clawclaw` 或 `clawclaw-creator`。描述说明适用场景,正文写清执行步骤、信息边界和完成条件;不要复制过时的游戏命令、写入凭据或要求绕过官方开局流程。
40
+ 写文件前用 `ccl capability list` 检查现有 Skill 的 `declaredId`、`relativePath` 和 `reserved_skill_names`,并确认目标目录不存在。遇到同名时可以选择未占用的后缀,例如把新 Skill 的目录和 `name` 都写为 `my-game-helper_1`。目录名与 `name` 保持一致。使用唯一名称;名称以字母或数字开头,后续只使用字母、数字、点、下划线或连字符,总长度不超过 128 字符。不要占用官方技能名称 `clawclaw` 或 `clawclaw-creator`。描述说明适用场景,正文写清执行步骤、信息边界和完成条件;不要复制过时的游戏命令、写入凭据或要求绕过官方开局流程。
41
41
 
42
42
  ## 本地装配与汇报
43
43
 
@@ -1,5 +1,5 @@
1
1
  import { accountRequiredMessage } from '../lib/desktop-mode.js';
2
- import { isPackageManagedSkill } from '../lib/package-skills.js';
2
+ import { isPackageManagedSkill, PACKAGE_MANAGED_SKILL_NAMES } from '../lib/package-skills.js';
3
3
  import { Command, InvalidArgumentError } from 'commander';
4
4
  import { AuthStore, type AuthProfile } from '../lib/auth.js';
5
5
  import { discoverLocalCapabilities } from '../lib/capability-discovery.js';
@@ -240,10 +240,12 @@ export function createCapabilityCommand(dependencies: CapabilityCommandDependenc
240
240
  .action(() => {
241
241
  const workspaceDir = getWorkspaceDir();
242
242
  const profile = activeProfile();
243
- discoverLocalCapabilities(workspaceDir, profile);
243
+ const { reservedSkills } = discoverLocalCapabilities(workspaceDir, profile);
244
244
  console.log(JSON.stringify({
245
245
  capabilities: Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
246
246
  .map(entry => ({ ...entry, selection_ref: capabilitySelectionRef(entry) })),
247
+ reserved_skill_names: PACKAGE_MANAGED_SKILL_NAMES,
248
+ ...(reservedSkills.length ? { skipped_skills: reservedSkills } : {}),
247
249
  }, null, 2));
248
250
  }));
249
251
 
@@ -919,10 +919,12 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
919
919
  } : undefined;
920
920
  const selectionRequired = pendingCapabilitySelections(workspaceDir, profile);
921
921
  const blockedSkillNames = skillConflictNames(skillChanges.conflicts ?? []);
922
+ const reservedSkillPaths = new Set(discoveredLocal.reservedSkills.map(skill => skill.path));
922
923
  const skills = [...new Set(Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
923
924
  .filter((entry) => entry.type === 'skill' && entry.selection === 'equipped'
924
925
  && !blockedSkillNames.has(skillNameKey(entry.runtimeId))
925
- && !entry.hub?.cloudStatus && !isPackageManagedSkill(entry.runtimeId))
926
+ && !entry.hub?.cloudStatus && !isPackageManagedSkill(entry.runtimeId)
927
+ && !reservedSkillPaths.has(capabilityWorkspacePath(workspaceDir, profile, entry)))
926
928
  .map((entry) => entry.runtimeId).concat((skillChanges.conflicts ?? [])
927
929
  .flatMap(item => item.active ? [item.active.id ?? item.active.name] : [])))].sort();
928
930
  console.log(JSON.stringify({
@@ -936,8 +938,9 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
936
938
  revision: activeWorkspace?.revision ?? null,
937
939
  ...(workspaceSyncError ? { error: workspaceSyncError } : {}),
938
940
  },
939
- ...(skillChangeSummary || cloudChangeSummary ? {
941
+ ...(skillChangeSummary || cloudChangeSummary || discoveredLocal.reservedSkills.length ? {
940
942
  changes: {
943
+ ...(discoveredLocal.reservedSkills.length ? { skipped_local_skills: discoveredLocal.reservedSkills } : {}),
941
944
  ...(skillChangeSummary ? { skills: skillChangeSummary } : {}),
942
945
  ...(cloudChangeSummary ? { cloud_sync: cloudChangeSummary } : {}),
943
946
  },
@@ -1,4 +1,4 @@
1
- import { isPackageManagedSkill } from './package-skills.js';
1
+ import { isPackageManagedSkill, reservedSkillName } from './package-skills.js';
2
2
  import {
3
3
  existsSync,
4
4
  lstatSync,
@@ -232,8 +232,10 @@ function accountManagedSkillSources(
232
232
  ? entry.hub?.resourceId === manifestEntry.resourceId
233
233
  : capabilityWorkspacePath(workspaceDir, profile, entry) === manifestEntry.canonicalPath));
234
234
  if (conflictingNames.has(skillNameKey(name)) && entry?.selection !== 'equipped') continue;
235
- if (!includeInactive && entry && (entry.selection !== 'equipped' || entry.hub?.cloudStatus)) continue;
236
- sources.set(name, manifestEntry.canonicalPath ?? join(skillsRoot, name));
235
+ const path = manifestEntry.canonicalPath ?? join(skillsRoot, name);
236
+ if (!includeInactive && (reservedSkillName(readSkillName(path), path)
237
+ || (entry && (entry.selection !== 'equipped' || entry.hub?.cloudStatus)))) continue;
238
+ sources.set(name, path);
237
239
  }
238
240
  for (const entry of Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)) {
239
241
  if (
@@ -243,7 +245,9 @@ function accountManagedSkillSources(
243
245
  || entry.selection !== 'equipped'
244
246
  || conflictingNames.has(skillNameKey(entry.runtimeId))
245
247
  ) continue;
246
- sources.set(entry.runtimeId, capabilityWorkspacePath(workspaceDir, profile, entry));
248
+ const path = capabilityWorkspacePath(workspaceDir, profile, entry);
249
+ if (!includeInactive && reservedSkillName(readSkillName(path), path)) continue;
250
+ sources.set(entry.runtimeId, path);
247
251
  }
248
252
  return sources;
249
253
  }
@@ -383,11 +387,12 @@ export function syncAgentWorkspaceSkills(
383
387
  const path = capabilityWorkspacePath(workspaceDir, profile, entry);
384
388
  const name = readSkillName(path) ?? entry.runtimeId;
385
389
  if (blockedNames.has(skillNameKey(name))) continue;
386
- if (isPackageManagedSkill(entry.runtimeId)) {
390
+ const reserved = reservedSkillName(entry.runtimeId) ?? reservedSkillName(name, path);
391
+ if (reserved) {
387
392
  failed.push({
388
- name: entry.runtimeId,
393
+ name: reserved,
389
394
  action: 'add',
390
- error: `The official ${entry.runtimeId} Skill is managed by the installed CCL package`,
395
+ error: `The official ${reserved} Skill is managed by the installed CCL package`,
391
396
  });
392
397
  continue;
393
398
  }
@@ -1,4 +1,4 @@
1
- import { isPackageManagedSkill } from './package-skills.js';
1
+ import { reservedSkillName } from './package-skills.js';
2
2
  import {
3
3
  existsSync,
4
4
  lstatSync,
@@ -64,7 +64,7 @@ export interface CapabilityCloudSyncFailure extends Partial<HubErrorFields> {
64
64
  export interface CapabilityCloudSyncSkip {
65
65
  type: CapabilityWorkspaceType;
66
66
  id: string;
67
- reason: 'local_origin_unrecognized' | 'fork_relationship_unresolved' | 'skill_name_conflict';
67
+ reason: 'local_origin_unrecognized' | 'fork_relationship_unresolved' | 'skill_name_conflict' | 'reserved_skill_name';
68
68
  }
69
69
 
70
70
  export interface CapabilityCloudSyncResult {
@@ -251,14 +251,20 @@ export async function syncCapabilitiesToCloud(
251
251
  ? [item.resourceId, item.forkReconciliation.parentResourceId] : []));
252
252
  const entries = Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
253
253
  .filter((entry) => (
254
- (entry.type !== 'skill' || !isPackageManagedSkill(entry.runtimeId))
255
- && !entry.hub?.cloudStatus
254
+ !entry.hub?.cloudStatus
256
255
  && (!selectedKeys || selectedKeys.has(entry.key))
257
256
  ));
258
257
  for (const entry of entries) {
259
- if (entry.type === 'skill' && blockedSkillNames.has(skillNameKey(skillNameCandidate(workspaceDir, profile, entry).name))) {
260
- result.skipped.push({ type: entry.type, id: entry.runtimeId, reason: 'skill_name_conflict' });
261
- continue;
258
+ if (entry.type === 'skill') {
259
+ const skill = skillNameCandidate(workspaceDir, profile, entry);
260
+ if (reservedSkillName(entry.runtimeId) || reservedSkillName(skill.name, skill.working_copy_path)) {
261
+ result.skipped.push({ type: entry.type, id: entry.runtimeId, reason: 'reserved_skill_name' });
262
+ continue;
263
+ }
264
+ if (blockedSkillNames.has(skillNameKey(skill.name))) {
265
+ result.skipped.push({ type: entry.type, id: entry.runtimeId, reason: 'skill_name_conflict' });
266
+ continue;
267
+ }
262
268
  }
263
269
  if (entry.hub && (entry.hub.forkRelationshipUnresolved || unresolvedForks.has(entry.hub.resourceId))) {
264
270
  result.skipped.push({ type: entry.type, id: entry.runtimeId, reason: 'fork_relationship_unresolved' });
@@ -1,4 +1,4 @@
1
- import { isPackageManagedSkill } from './package-skills.js';
1
+ import { reservedSkillName } from './package-skills.js';
2
2
  import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import type { AuthProfile } from './auth.js';
@@ -31,6 +31,7 @@ export interface DiscoveredLocalCapabilities {
31
31
  perceptions: Array<{ source: ResolvedClawclawPerceptionSource; entry: CapabilityWorkspaceEntry }>;
32
32
  personas: CapabilityWorkspaceEntry[];
33
33
  skills: CapabilityWorkspaceEntry[];
34
+ reservedSkills: Array<{ name: string; path: string; reason: 'reserved_skill_name' }>;
34
35
  }
35
36
 
36
37
  export function discoverLocalCapabilities(
@@ -73,6 +74,7 @@ export function discoverLocalCapabilities(
73
74
  description: `Persona ${preset.name}`,
74
75
  }));
75
76
  const skillsRoot = getUserDataAccountSkillsDir(workspaceDir, profile);
77
+ const reservedSkills: DiscoveredLocalCapabilities['reservedSkills'] = [];
76
78
  const skills = existsSync(skillsRoot)
77
79
  ? readdirSync(skillsRoot, { withFileTypes: true }).flatMap((item) => {
78
80
  if (!item.isDirectory()) return [];
@@ -83,7 +85,12 @@ export function discoverLocalCapabilities(
83
85
  return [];
84
86
  }
85
87
  const name = readSkillName(path);
86
- return name && !isPackageManagedSkill(name) ? [registerDiscoveredCapability(workspaceDir, profile, {
88
+ const reserved = reservedSkillName(name, path);
89
+ if (reserved) {
90
+ reservedSkills.push({ name: reserved, path, reason: 'reserved_skill_name' });
91
+ return [];
92
+ }
93
+ return name ? [registerDiscoveredCapability(workspaceDir, profile, {
87
94
  type: 'skill',
88
95
  path,
89
96
  runtimeId: name,
@@ -95,6 +102,6 @@ export function discoverLocalCapabilities(
95
102
  return {
96
103
  behaviors: behaviors.map(({ source, entry }) => ({ source: behaviorOperationName(source, entry), entry })),
97
104
  perceptions: perceptions.map(({ source, entry }) => ({ source: perceptionOperationName(source, entry), entry })),
98
- personas, skills,
105
+ personas, skills, reservedSkills,
99
106
  };
100
107
  }
@@ -1,5 +1,7 @@
1
1
  import type { AuthProfile } from './auth.js';
2
2
  import { HubClient } from './hub-client.js';
3
+ import { reservedSkillName } from './package-skills.js';
4
+ import { CommandOutputError } from './command-error.js';
3
5
  import { assignCapabilityOperationName, capabilitySelectionRef,
4
6
  readCapabilityWorkspaceRegistry, writeCapabilityWorkspaceRegistry,
5
7
  type CapabilityWorkspaceType } from './capability-workspace.js';
@@ -27,6 +29,11 @@ export async function selectCapability(
27
29
  if (matches.length !== 1) throw new Error(`capability_selection_${matches.length ? 'ambiguous' : 'not_found'}:${type}:${id}`);
28
30
  const entry = matches[0]!;
29
31
  if (type === 'skill' && equipped) {
32
+ const skill = skillNameCandidate(workspaceDir, profile, entry);
33
+ const reserved = reservedSkillName(entry.runtimeId) ?? reservedSkillName(skill.name, skill.working_copy_path);
34
+ if (reserved) throw new CommandOutputError(`reserved_skill_name:${reserved}`, {
35
+ error: 'reserved_skill_name', name: reserved, path: skill.working_copy_path, retryable: false,
36
+ });
30
37
  const candidates = Object.values(registry.entries).filter(other => other.type === 'skill'
31
38
  && (other.key === entry.key || (other.selection === 'equipped' && !other.hub?.cloudStatus)));
32
39
  const conflict = skillNameConflicts(candidates.map(other => skillNameCandidate(workspaceDir, profile, other)))
@@ -25,10 +25,13 @@ import type {
25
25
  } from './room.js';
26
26
  import { synthesizeConfiguredTts } from './custom-tts.js';
27
27
  import type { TransportResponse } from '../short-command/transport-response.js';
28
+ import { lobbyHostHeaders, resolveLobbyHostContext, validateLobbyHostContext, type LobbyHostContext } from './lobby-host-context.js';
28
29
 
29
30
  export { ApiError } from './http-transport.js';
30
31
 
31
32
  export interface GameClientConfig {
33
+ /** One stable host context for Lobby participation and socket reconnects. */
34
+ hostContext?: LobbyHostContext;
32
35
  lobbyUrl: string;
33
36
  gameServerUrl?: string;
34
37
  apiKey: string;
@@ -72,6 +75,8 @@ function agentMetadataHeaders(options: RoomEntryMetadata): Record<string, string
72
75
  }
73
76
 
74
77
  export class GameClient {
78
+ private resolvedHostContext?: LobbyHostContext;
79
+ private readonly hostEnvironment: NodeJS.ProcessEnv;
75
80
  private http: HttpTransport;
76
81
  private ws: Pick<WsClient, keyof WsClient> | null = null;
77
82
  private readonly gameSyncIngress?: GameClientConfig['gameSyncIngress'];
@@ -115,6 +120,12 @@ export class GameClient {
115
120
  }
116
121
 
117
122
  constructor(config: GameClientConfig) {
123
+ this.resolvedHostContext = config.hostContext ? validateLobbyHostContext(config.hostContext) : undefined;
124
+ this.hostEnvironment = {
125
+ CLAWCLAW_IS_DESKTOP: process.env.CLAWCLAW_IS_DESKTOP,
126
+ CLAWCLAW_HOST_INSTANCE_ID: process.env.CLAWCLAW_HOST_INSTANCE_ID,
127
+ CLAWCLAW_HOST_SESSION_ID: process.env.CLAWCLAW_HOST_SESSION_ID,
128
+ };
118
129
  this.apiKey = config.apiKey;
119
130
  this.enableWs = config.enableWs ?? false;
120
131
  this.rawWsMessageSink = config.rawWsMessageSink;
@@ -318,6 +329,24 @@ export class GameClient {
318
329
 
319
330
  // ─── Queue API (→ lobby, auto game server discovery) ───
320
331
 
332
+ /** Lazy so login, Hub and read-only status remain usable before host setup. */
333
+ get lobbyHostContext(): LobbyHostContext {
334
+ return this.resolvedHostContext ??= resolveLobbyHostContext(this.hostEnvironment);
335
+ }
336
+
337
+ private async enterLobby(path: string, body: unknown, metadata: RoomEntryMetadata): Promise<any> {
338
+ const response = await this.http.postRaw(path, body, {
339
+ ...agentMetadataHeaders(metadata),
340
+ ...lobbyHostHeaders(this.lobbyHostContext),
341
+ });
342
+ if (response.status < 200 || response.status >= 300
343
+ || (response.body.kind === 'json' && (response.body.value as { success?: unknown } | null)?.success === false)) {
344
+ throw new ApiError(response.status, response.body.rawText, 'POST', path, response);
345
+ }
346
+ if (response.body.kind !== 'json') throw new SyntaxError(`Unexpected non-JSON response from ${path}`);
347
+ return response.body.value;
348
+ }
349
+
321
350
 
322
351
 
323
352
  async joinQueue(options: string | { gameType?: string; mode?: QueueMode; agentType?: string; monitorStatus?: 'on' | 'off'; llmModel?: string } = 'clawclaw'): Promise<any> {
@@ -331,8 +360,7 @@ export class GameClient {
331
360
  // X-Agent-Type — the agent platform (e.g. claude-code, openclaw)
332
361
  // X-Monitor-Status — whether the Claude Code Monitor tool is on/off this match
333
362
  // X-LLM-Model — the exact/canonical reasoning model ID the lobster (龙虾) agent runs as this match
334
- const headers = agentMetadataHeaders({ agentType, monitorStatus, llmModel });
335
- const result = await this.http.post('/api/v1/queue/join', { game_type: gameType, mode }, headers);
363
+ const result = await this.enterLobby('/api/v1/queue/join', { game_type: gameType, mode }, { agentType, monitorStatus, llmModel });
336
364
  this.registry.updateFromQueueResponse(result);
337
365
  return result;
338
366
  }
@@ -359,14 +387,13 @@ export class GameClient {
359
387
 
360
388
  async createRoom(options: RoomType | CreateRoomOptions = {}): Promise<any> {
361
389
  const normalized = typeof options === 'string' ? { roomType: options } : options;
362
- const headers = agentMetadataHeaders(normalized);
363
390
  return normalized.roomType
364
- ? this.http.post('/api/v1/room/create', { room_type: normalized.roomType }, headers)
365
- : this.http.post('/api/v1/room/create', undefined, headers);
391
+ ? this.enterLobby('/api/v1/room/create', { room_type: normalized.roomType }, normalized)
392
+ : this.enterLobby('/api/v1/room/create', undefined, normalized);
366
393
  }
367
394
 
368
395
  async joinRoom(roomCode: string, metadata: RoomEntryMetadata = {}): Promise<any> {
369
- return this.http.post('/api/v1/room/join', { room_code: roomCode }, agentMetadataHeaders(metadata));
396
+ return this.enterLobby('/api/v1/room/join', { room_code: roomCode }, metadata);
370
397
  }
371
398
 
372
399
  async getRoomStatus(): Promise<any> {
@@ -0,0 +1,74 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { isDesktopMode } from './desktop-mode.js';
3
+ import { ApiError } from './http-transport.js';
4
+
5
+ /** Participation origin, not an authentication or GameSync session identity. */
6
+ export type LobbyHostContext =
7
+ | { readonly host_type: 'desktop'; readonly host_instance_id: string; readonly host_session_id: string }
8
+ | { readonly host_type: 'agent' | 'browser'; readonly host_instance_id: string; readonly host_session_id: null };
9
+
10
+ const agentInstanceId = randomUUID();
11
+
12
+ export class InvalidHostContextError extends Error {
13
+ readonly code = 'INVALID_HOST_CONTEXT';
14
+ constructor(message: string) {
15
+ super(`INVALID_HOST_CONTEXT: ${message}`);
16
+ this.name = 'InvalidHostContextError';
17
+ }
18
+ }
19
+
20
+ function validId(value: unknown): value is string {
21
+ return typeof value === 'string' && [...value].length >= 1 && [...value].length <= 128
22
+ && !/[\p{White_Space}\p{Cc}]/u.test(value);
23
+ }
24
+
25
+ /** Unknown/legacy origins stay unknown; never fill them from the receiving client. */
26
+ export function parseLobbyParticipation(value: unknown): LobbyHostContext | null {
27
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
28
+ const host = value as Record<string, unknown>;
29
+ if (!validId(host.host_instance_id)) return null;
30
+ if (host.host_type === 'desktop' && validId(host.host_session_id)) {
31
+ return { host_type: 'desktop', host_instance_id: host.host_instance_id, host_session_id: host.host_session_id };
32
+ }
33
+ if ((host.host_type === 'agent' || host.host_type === 'browser') && host.host_session_id === null) {
34
+ return { host_type: host.host_type, host_instance_id: host.host_instance_id, host_session_id: null };
35
+ }
36
+ return null;
37
+ }
38
+
39
+ export function validateLobbyHostContext(value: LobbyHostContext): LobbyHostContext {
40
+ const host = parseLobbyParticipation(value);
41
+ if (!host) throw new InvalidHostContextError('Host IDs must be 1–128 characters without whitespace or control characters; desktop requires a session ID.');
42
+ return Object.freeze(host);
43
+ }
44
+
45
+ export function resolveLobbyHostContext(env: NodeJS.ProcessEnv = process.env): LobbyHostContext {
46
+ const instanceId = env.CLAWCLAW_HOST_INSTANCE_ID;
47
+ const sessionId = env.CLAWCLAW_HOST_SESSION_ID;
48
+ if (isDesktopMode(env)) {
49
+ if (!validId(instanceId) || !validId(sessionId)) {
50
+ throw new InvalidHostContextError('Desktop must provide CLAWCLAW_HOST_INSTANCE_ID and CLAWCLAW_HOST_SESSION_ID (1–128 characters, no whitespace/control characters).');
51
+ }
52
+ return Object.freeze({ host_type: 'desktop', host_instance_id: instanceId, host_session_id: sessionId });
53
+ }
54
+ if (sessionId !== undefined) {
55
+ throw new InvalidHostContextError('CLAWCLAW_HOST_SESSION_ID is only valid with CLAWCLAW_IS_DESKTOP=true; omit it for standalone agents.');
56
+ }
57
+ return validateLobbyHostContext({ host_type: 'agent', host_instance_id: instanceId ?? agentInstanceId, host_session_id: null });
58
+ }
59
+
60
+ export function lobbyHostHeaders(host: LobbyHostContext): Record<string, string> {
61
+ const valid = validateLobbyHostContext(host);
62
+ return {
63
+ 'X-Host-Type': valid.host_type,
64
+ 'X-Host-Instance-Id': valid.host_instance_id,
65
+ ...(valid.host_type === 'desktop' ? { 'X-Host-Session-Id': valid.host_session_id } : {}),
66
+ };
67
+ }
68
+
69
+ export function isInvalidHostContextError(error: unknown): boolean {
70
+ if (error instanceof InvalidHostContextError) return true;
71
+ if (!(error instanceof ApiError)) return false;
72
+ try { return JSON.parse(error.body)?.error?.code === 'INVALID_HOST_CONTEXT'; }
73
+ catch { return false; }
74
+ }
@@ -1,4 +1,14 @@
1
+ import { basename } from 'node:path';
2
+
1
3
  /** Package-owned teaching skills are independent of an account's Hub loadout. */
4
+ export const PACKAGE_MANAGED_SKILL_NAMES = ['clawclaw', 'clawclaw-creator'] as const;
5
+
6
+ export function reservedSkillName(name: string | null, directory?: string): string | undefined {
7
+ const key = name?.trim().toLowerCase();
8
+ const folder = directory && basename(directory).trim().toLowerCase();
9
+ return PACKAGE_MANAGED_SKILL_NAMES.find(reserved => reserved === key || reserved === folder);
10
+ }
11
+
2
12
  export function isPackageManagedSkill(name: string | null): boolean {
3
- return name === 'clawclaw' || name === 'clawclaw-creator';
13
+ return reservedSkillName(name) !== undefined;
4
14
  }
@@ -7,6 +7,7 @@ import {
7
7
  queueStatus,
8
8
  unwrapData,
9
9
  } from './room.js';
10
+ import { parseLobbyParticipation, type LobbyHostContext } from './lobby-host-context.js';
10
11
 
11
12
  export const GAME_STATUS_SCHEMA = 'ccl.game-status.v1' as const;
12
13
 
@@ -28,6 +29,8 @@ export interface GameParticipationStatus {
28
29
  room_type?: string;
29
30
  room_status?: string;
30
31
  game_id?: string;
32
+ /** Backend participation origin. Null means unknown; absent while idle/matching. */
33
+ origin?: LobbyHostContext | null;
31
34
  }
32
35
 
33
36
  export interface ParticipationStatusClient {
@@ -74,6 +77,8 @@ export async function queryGameParticipationStatus(
74
77
  schema: GAME_STATUS_SCHEMA,
75
78
  status,
76
79
  queue_status: currentQueueStatus,
80
+ ...((currentQueueStatus === 'in_room' || currentQueueStatus === 'allocated')
81
+ ? { origin: parseLobbyParticipation(queue?.participation) } : {}),
77
82
  }, {
78
83
  mode,
79
84
  room_code: roomCode,
@@ -626,6 +626,8 @@ function shortBody(event: Record<string, any>, ctx: EventFormatContext): string
626
626
  return '房间对局已结束,但账号已不在原房间。';
627
627
  case 'room_ping_timeout':
628
628
  return '房间 Lobby 连接心跳超时,正在重连。';
629
+ case 'lobby_connection_replaced':
630
+ return '大厅连接已被替换或登记已失效,已停止自动重连。需要继续时请明确发起接续。';
629
631
  case 'robot_speak_rule':
630
632
  return `发言提示:${truncate(event.message ?? event.text, maxTextLength)}`;
631
633
  case 'strategy_alert':
@@ -271,6 +271,7 @@ export const BACKEND_EVENT_HINT_FORMATTERS: Readonly<Record<string, EventHintFor
271
271
  });
272
272
 
273
273
  export const LOCAL_LIFECYCLE_EVENT_HINT_FORMATTERS: Readonly<Record<string, EventHintFormatter>> = Object.freeze({
274
+ lobby_connection_replaced: () => 'The Lobby connection was replaced or its registration expired. Automatic reconnection has stopped. Tell the user and resume only after an explicit request; do not automatically run ccl join, start another runtime, log out, or leave the room/game.',
274
275
  joined: (event) => {
275
276
  if (typeof event.url !== 'string' || event.url.length === 0) return undefined;
276
277
  return event.recovered === true || event.resumed === true
@@ -1,9 +1,14 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import type { ClawclawResolvedResourceMetadata } from '../../sdk/behavior-plugin/index.js';
1
3
  import type { Runtime } from '../framework/runtime.js';
2
4
  import type { OwnerControlResponse } from '../owner-control.js';
3
5
  import type { ClawclawBehaviorPlugin } from './plugins/behavior/behavior-plugin.js';
4
6
 
5
7
  type StartRuntime = Pick<Runtime, 'publicScope' | 'currentSegment' | 'readState'>;
6
8
  type BehaviorStarter = Pick<ClawclawBehaviorPlugin, 'startLong' | 'startShort'>;
9
+ type DeferredStartRuntime = StartRuntime & Pick<Runtime, 'diagnostic'> & {
10
+ readReadyView(): Pick<ReturnType<Runtime['readReadyView']>, 'state'>;
11
+ };
7
12
 
8
13
  interface BehaviorStartRequest {
9
14
  expectedScope: Readonly<{ sessionId: string; segmentId: string }>;
@@ -50,10 +55,14 @@ export async function startOwnerBehavior(
50
55
  runtime: StartRuntime,
51
56
  behavior: BehaviorStarter,
52
57
  request: BehaviorStartRequest,
58
+ canStart: () => boolean = () => true,
53
59
  ): Promise<OwnerControlResponse> {
54
60
  let rejection: OwnerControlResponse | undefined;
55
61
  const isCurrent = (): boolean => {
56
62
  rejection = startRejection(runtime, request);
63
+ if (!rejection && !canStart()) {
64
+ rejection = { ok: false, type: 'behavior_start', error: 'deferred_strategy_not_ready' };
65
+ }
57
66
  return rejection === undefined;
58
67
  };
59
68
  if (!isCurrent()) return rejection!;
@@ -77,3 +86,108 @@ export async function startOwnerBehavior(
77
86
  };
78
87
  }
79
88
  }
89
+
90
+ /** One explicit short selection per game. GAR still owns actual activations. */
91
+ export class DeferredMeetingShortStrategy {
92
+ private requestVersion = 0;
93
+ private pending?: {
94
+ request: BehaviorStartRequest;
95
+ requestId: string;
96
+ display: ClawclawResolvedResourceMetadata;
97
+ starting: boolean;
98
+ };
99
+
100
+ constructor(
101
+ private readonly runtime: DeferredStartRuntime,
102
+ private readonly behavior: BehaviorStarter & Pick<ClawclawBehaviorPlugin, 'cancel'>,
103
+ private readonly resolveDisplay: (request: BehaviorStartRequest) => ClawclawResolvedResourceMetadata | undefined,
104
+ ) {}
105
+
106
+ async start(request: BehaviorStartRequest): Promise<OwnerControlResponse> {
107
+ const rejection = startRejection(this.runtime, request);
108
+ if (rejection) return rejection;
109
+ if (request.layer !== 'short') return startOwnerBehavior(this.runtime, this.behavior, request);
110
+ const version = ++this.requestVersion;
111
+ const inMeeting = () => this.runtime.readState().state?.phase === 'meeting';
112
+ if (!inMeeting()) {
113
+ this.pending = undefined;
114
+ const result = await startOwnerBehavior(this.runtime, this.behavior, request,
115
+ () => version === this.requestVersion && !inMeeting());
116
+ if (version !== this.requestVersion || result.error !== 'deferred_strategy_not_ready' || !inMeeting()) return result;
117
+ const latestRejection = startRejection(this.runtime, request);
118
+ if (latestRejection) return latestRejection;
119
+ }
120
+ try {
121
+ const display = this.resolveDisplay(request);
122
+ if (!display) return { ok: false, type: 'behavior_start', error: 'behavior_not_found' };
123
+ this.pending = { request: structuredClone(request), requestId: randomUUID(), display, starting: false };
124
+ return { ok: true, type: 'behavior_start', status: 'queued', pending: this.status() };
125
+ } catch (error) {
126
+ return { ok: false, type: 'behavior_start', error: error instanceof Error ? error.message : String(error) };
127
+ }
128
+ }
129
+
130
+ status(behaviorId?: string) {
131
+ const pending = this.currentPending();
132
+ if (!pending || (behaviorId && pending.request.behavior !== behaviorId)) return undefined;
133
+ return {
134
+ request_id: pending.requestId, behavior: pending.request.behavior, layer: 'short' as const,
135
+ status: pending.starting ? 'starting' : 'waiting_for_wandering',
136
+ };
137
+ }
138
+
139
+ display(): ClawclawResolvedResourceMetadata | undefined {
140
+ return this.currentPending()?.display;
141
+ }
142
+
143
+ cancel(requestId: string): boolean {
144
+ if (this.currentPending()?.requestId !== requestId) return false;
145
+ this.pending = undefined;
146
+ return true;
147
+ }
148
+
149
+ afterReady(): void {
150
+ const pending = this.currentPending();
151
+ if (!pending || pending.starting || this.runtime.readState().state?.phase !== 'wandering'
152
+ || this.runtime.readReadyView().state.state?.phase !== 'wandering') return;
153
+ pending.starting = true;
154
+ void this.activate(pending).catch(error => {
155
+ this.runtime.diagnostic('behavior.deferred_short.failed', {
156
+ behavior_id: pending.request.behavior,
157
+ error: error instanceof Error ? error.message : String(error),
158
+ }, 'warn');
159
+ });
160
+ }
161
+
162
+ private currentPending() {
163
+ const pending = this.pending;
164
+ if (!pending) return undefined;
165
+ const rejection = startRejection(this.runtime, pending.request);
166
+ if (rejection && rejection.code !== 'GAME_STATE_UNAVAILABLE') {
167
+ this.pending = undefined;
168
+ return undefined;
169
+ }
170
+ return pending;
171
+ }
172
+
173
+ private async activate(pending: NonNullable<DeferredMeetingShortStrategy['pending']>): Promise<void> {
174
+ const canStart = () => this.pending === pending && this.runtime.readState().state?.phase === 'wandering';
175
+ const result = await startOwnerBehavior(this.runtime, this.behavior, pending.request, canStart);
176
+ if (this.pending !== pending) {
177
+ // Cancellation or replacement can arrive while the new runner starts.
178
+ const activationId = result.ok && result.activation?.activationId;
179
+ if (typeof activationId === 'string') await this.behavior.cancel(activationId, 'deferred_short_superseded');
180
+ return;
181
+ }
182
+ if (result.error === 'deferred_strategy_not_ready' || result.code === 'GAME_STATE_UNAVAILABLE') {
183
+ pending.starting = false;
184
+ return;
185
+ }
186
+ this.pending = undefined;
187
+ if (!result.ok) {
188
+ this.runtime.diagnostic('behavior.deferred_short.failed', {
189
+ behavior_id: pending.request.behavior, error: result.error,
190
+ }, 'warn');
191
+ }
192
+ }
193
+ }
@@ -12,6 +12,7 @@ export const CLAWCLAW_SYSTEM_CONTROL_EVENTS = new Set([
12
12
  'match_start', 'match_waiting', 'match_timeout', 'user_left_game', 'session_left', 'quit_failed',
13
13
  'room_attached', 'room_lobby_reconnect_failed', 'room_lobby_missing', 'room_returning_to_lobby',
14
14
  'room_ping_timeout', 'room_destroyed', 'room.self_left', 'room.game_start_failed',
15
+ 'lobby_connection_replaced',
15
16
  ]);
16
17
 
17
18
  export const BUILTIN_PERCEPTION_PREFIX = 'clawclaw.perception.system.';