@myclaw163/clawclaw-cli 0.10.7 → 0.10.9

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 (64) hide show
  1. package/README.md +6 -4
  2. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/host.js +1 -0
  3. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-sdk.js +79 -5
  4. package/docs/configuration.md +4 -7
  5. package/docs/custom-modules/README.md +1 -1
  6. package/docs/custom-modules/behavior.md +2 -2
  7. package/docs/custom-modules/perception.md +1 -1
  8. package/docs/custom-modules/skill.md +6 -5
  9. package/docs/desktop-event-push.md +2 -1
  10. package/docs/runtime/README.md +1 -1
  11. package/docs/runtime/agent-notifications.md +1 -1
  12. package/docs/runtime/official-perception-modules.md +2 -2
  13. package/docs/user-guide/README.md +1 -1
  14. package/docs/user-guide/behavior.md +3 -2
  15. package/docs/user-guide/desktop-auth.md +33 -1
  16. package/docs/user-guide/installation.md +7 -6
  17. package/docs/user-guide/perception.md +1 -1
  18. package/docs/user-guide/skill.md +6 -5
  19. package/package.json +1 -1
  20. package/scripts/check-skill-command-surface.mjs +7 -2
  21. package/scripts/enable_ccl_permissions.cjs +4 -0
  22. package/skills/clawclaw/SKILL.md +24 -188
  23. package/skills/clawclaw/references/BEHAVIORS.md +7 -7
  24. package/skills/clawclaw/references/CHANNELS.md +1 -1
  25. package/skills/clawclaw/references/COMMANDS.md +20 -18
  26. package/skills/clawclaw/references/HUB.md +15 -15
  27. package/skills/clawclaw/references/STREAM.md +1 -1
  28. package/skills/clawclaw-creator/SKILL.md +27 -25
  29. package/skills/clawclaw-creator/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +9 -9
  30. package/skills/clawclaw-creator/references/CUSTOM-MODULE-API.md +5 -5
  31. package/skills/clawclaw-creator/references/CUSTOM-MODULES.md +14 -13
  32. package/skills/clawclaw-creator/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +7 -7
  33. package/skills/clawclaw-creator/references/CUSTOM-PERSONA-DEVELOPMENT.md +6 -6
  34. package/skills/clawclaw-creator/references/CUSTOM-SKILL-DEVELOPMENT.md +11 -10
  35. package/skills/clawclaw-creator/references/SYNC-AND-REPORT.md +21 -19
  36. package/skills/clawclaw-start/SKILL.md +49 -0
  37. package/skills/clawclaw-start/references/STARTUP.md +176 -0
  38. package/src/cli.ts +2 -0
  39. package/src/commands/behavior.ts +1 -1
  40. package/src/commands/communication.ts +1 -1
  41. package/src/commands/hub.ts +2 -2
  42. package/src/commands/load.ts +30 -984
  43. package/src/commands/prepare.ts +1002 -0
  44. package/src/commands/skill.ts +1 -1
  45. package/src/lib/account-guidance.ts +5 -3
  46. package/src/lib/game-client.ts +33 -6
  47. package/src/lib/hub-errors.ts +2 -2
  48. package/src/lib/load-context.ts +11 -7
  49. package/src/lib/load-startup-context.ts +85 -0
  50. package/src/lib/load-startup.ts +47 -0
  51. package/src/lib/lobby-host-context.ts +74 -0
  52. package/src/lib/package-skills.ts +1 -1
  53. package/src/lib/participation-status.ts +5 -0
  54. package/src/lib/skill-name-conflicts.ts +1 -1
  55. package/src/pipeline/event-format.ts +2 -0
  56. package/src/pipeline/event-hints.ts +3 -2
  57. package/src/runtime/auto-upgrade.ts +1 -1
  58. package/src/runtime/clawclaw/notification-policy.ts +1 -0
  59. package/src/runtime/clawclaw/owner.ts +2 -7
  60. package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-perception-report-adapter.ts +3 -3
  61. package/src/runtime/clawclaw/plugins/source/room-transport.ts +46 -9
  62. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +18 -4
  63. package/src/runtime/clawclaw/plugins/source/types.ts +2 -0
  64. package/src/runtime/clawclaw-event-catalog.ts +1 -0
@@ -46,7 +46,7 @@ export function createSkillCommand(): Command {
46
46
  // ─── install ───
47
47
  cmd.command('install [path]')
48
48
  .description('Register a skill directory with the agent. Use --builtin for all bundled ClawClaw skills.')
49
- .option('--builtin', 'install the bundled gameplay and creator skills shipped with this CLI')
49
+ .option('--builtin', 'install the bundled startup, gameplay and creator skills shipped with this CLI')
50
50
  .option('-g, --global', 'install globally', true)
51
51
  .option('-y, --yes', 'skip confirmation prompts', true)
52
52
  .action(async (rawPath: string | undefined, opts: { builtin?: boolean; global?: boolean; yes?: boolean }) => {
@@ -9,7 +9,7 @@ export const INVITE_RETRY_COMMAND = 'ccl account register --invite-code <code>';
9
9
  export const NAMED_INVITE_RETRY_COMMAND = 'ccl account register --name <name> --invite-code <code>';
10
10
 
11
11
  export const POST_REGISTRATION_NEXT_STEP =
12
- 'Ask the player whether to start matchmaking now. If yes, run `ccl load` first. When participation.status is `idle`, launch `ccl start match` with the host stream tool; if participation already exists, attach with `ccl join` instead.';
12
+ 'Ask the player whether to start matchmaking now. If yes, run `ccl prepare` first. When participation.status is `idle`, launch `ccl start match` with the host stream tool; if participation already exists, attach with `ccl join` instead.';
13
13
 
14
14
  // Player-facing scripts, spoken verbatim by the Agent. This is the only place
15
15
  // registration wording is defined, so the gated and ungated flows cannot drift.
@@ -54,7 +54,7 @@ export function registrationCheckOutput(result: RegistrationCheckResult): Record
54
54
  };
55
55
  }
56
56
 
57
- type NoAccountAction = 'load' | 'gameStart' | 'accountInfo';
57
+ type NoAccountAction = 'prepare' | 'load' | 'gameStart' | 'accountInfo';
58
58
 
59
59
  // Safety net for a caller that registered without checking the policy first.
60
60
  // No account was created, so the only thing missing is the code.
@@ -76,7 +76,9 @@ export function noAccountMessage(action: NoAccountAction): string {
76
76
  ? 'Cannot start matchmaking: no local ClawClaw account is configured.'
77
77
  : action === 'accountInfo'
78
78
  ? 'No local ClawClaw account is configured.'
79
- : 'Cannot load persona/memory: no local ClawClaw account is configured.';
79
+ : action === 'prepare'
80
+ ? 'Cannot prepare gameplay resources: no local ClawClaw account is configured.'
81
+ : 'Cannot load persona/memory: no local ClawClaw account is configured.';
80
82
  return [
81
83
  firstLine,
82
84
  REGISTRATION_PROMPT,
@@ -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> {
@@ -42,9 +42,9 @@ export function hubErrorFields(error: unknown): HubErrorFields | undefined {
42
42
  } else if (version && code === 'SKILL_NAME_KEY_MISSING') {
43
43
  result.hint = '该历史 Skill 尚未完成名称回填,请联系 Hub 运维处理后再发版;不要反复重试,本地修改已保留。';
44
44
  } else if (equipment && code === 'SKILL_NAME_CONFLICT') {
45
- result.hint = '已装配另一件同名 Skill。请用户到 Hub 处理装配冲突,完成后重新运行 ccl load;CCL 不自动卸载或替换任何 Skill,也不要用卸载后重装绕过此提示。';
45
+ result.hint = '已装配另一件同名 Skill。请用户到 Hub 处理装配冲突,完成后重新运行 ccl prepare;CCL 不自动卸载或替换任何 Skill,也不要用卸载后重装绕过此提示。';
46
46
  } else if (equipment && code === 'INVALID_LOADOUT') {
47
- result.hint = '装配选择无效,可能是同名 Skill、超出上限或类型不匹配。请按服务端原因到 Hub 修正选择,再运行 ccl load。';
47
+ result.hint = '装配选择无效,可能是同名 Skill、超出上限或类型不匹配。请按服务端原因到 Hub 修正选择,再运行 ccl prepare。';
48
48
  } else if (equipment && code === 'WORKSPACE_REVISION_CONFLICT') {
49
49
  result.hint = 'Workspace 装配正在被并发修改。请刷新最新装配状态后再重试本次明确操作;不要反复重放旧装配。';
50
50
  result.retryable = true;
@@ -30,20 +30,20 @@ function ensureMemoryFile(path: string): void {
30
30
  if (!existsSync(path)) writeFileSync(path, '');
31
31
  }
32
32
 
33
- export function loadPersonaSnapshot(authStore = new AuthStore()): LoadedFileSnapshot {
33
+ export function loadPersonaSnapshot(authStore = new AuthStore(), includeContent = true): LoadedFileSnapshot {
34
34
  const resolved = resolveActivePersonaFile(authStore);
35
35
  const exists = resolved.path !== null && existsSync(resolved.path);
36
36
  return {
37
37
  path: resolved.path,
38
38
  exists,
39
- content: resolved.path ? readPersonaFile(resolved.path) : '',
39
+ content: includeContent && resolved.path ? readPersonaFile(resolved.path) : '',
40
40
  source: resolved.source,
41
41
  ...(resolved.id ? { id: resolved.id } : {}),
42
42
  ...(resolved.resourceId ? { resource_id: resolved.resourceId } : {}),
43
43
  };
44
44
  }
45
45
 
46
- export function loadMemorySnapshot(authStore = new AuthStore()): LoadedFileSnapshot {
46
+ export function loadMemorySnapshot(authStore = new AuthStore(), includeContent = true): LoadedFileSnapshot {
47
47
  const profile = authStore.getActive();
48
48
  if (!profile) throw new Error(accountRequiredMessage('Not logged in.'));
49
49
  const path = getProfileMemoryFile(profile);
@@ -52,7 +52,7 @@ export function loadMemorySnapshot(authStore = new AuthStore()): LoadedFileSnaps
52
52
  return {
53
53
  path,
54
54
  exists,
55
- content: exists ? readFileSync(path, 'utf8') : '',
55
+ content: includeContent && exists ? readFileSync(path, 'utf8') : '',
56
56
  };
57
57
  }
58
58
 
@@ -81,9 +81,13 @@ export function limitMemoryForAgent(
81
81
  };
82
82
  }
83
83
 
84
- export function loadContext(authStore = new AuthStore()): LoadContextSnapshot {
84
+ export function loadContext(
85
+ authStore = new AuthStore(),
86
+ options: { includeContent?: boolean } = {},
87
+ ): LoadContextSnapshot {
88
+ const includeContent = options.includeContent !== false;
85
89
  return {
86
- persona: loadPersonaSnapshot(authStore),
87
- memory: limitMemoryForAgent(loadMemorySnapshot(authStore)),
90
+ persona: loadPersonaSnapshot(authStore, includeContent),
91
+ memory: limitMemoryForAgent(loadMemorySnapshot(authStore, includeContent)),
88
92
  };
89
93
  }
@@ -0,0 +1,85 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { mkdirSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import type { AuthProfile } from './auth.js';
5
+ import { getUserDataAccountDir } from './user-data.js';
6
+
7
+ const REF = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
8
+ const SCHEMA = 'ccl.startup-context.v1';
9
+ const RETAINED_CONTEXTS = 32;
10
+
11
+ export interface DeferredLoadContext {
12
+ sync: Record<string, unknown>;
13
+ changes?: Record<string, unknown>;
14
+ capabilities: Record<string, unknown>;
15
+ configuration_warnings: readonly Record<string, unknown>[];
16
+ persona_available: boolean;
17
+ }
18
+
19
+ interface StoredContext extends DeferredLoadContext {
20
+ schema: typeof SCHEMA;
21
+ context_ref: string;
22
+ prepared_at: string;
23
+ }
24
+
25
+ function directory(workspace: string, profile: Pick<AuthProfile, 'apiKey'>): string {
26
+ return join(getUserDataAccountDir(workspace, profile), 'startup-contexts');
27
+ }
28
+
29
+ /** Save notices and capability metadata without persona/memory text or a reusable participation snapshot. */
30
+ export function saveStartupContext(
31
+ workspace: string,
32
+ profile: Pick<AuthProfile, 'apiKey'>,
33
+ context: DeferredLoadContext,
34
+ ): { context_ref: string; prepared_at: string } {
35
+ const root = directory(workspace, profile);
36
+ mkdirSync(root, { recursive: true });
37
+ const context_ref = randomUUID();
38
+ const prepared_at = new Date().toISOString();
39
+ const value: StoredContext = { schema: SCHEMA, context_ref, prepared_at, ...context };
40
+ writeFileSync(join(root, `${context_ref}.json`), JSON.stringify(value), { flag: 'wx', mode: 0o600 });
41
+ const pointer = join(root, `${context_ref}.pointer`);
42
+ writeFileSync(pointer, context_ref, { flag: 'wx', mode: 0o600 });
43
+ renameSync(pointer, join(root, 'latest'));
44
+ const previous = readdirSync(root).filter(name => name.endsWith('.json')
45
+ && REF.test(name.slice(0, -5)) && name !== `${context_ref}.json`)
46
+ .map(name => ({ name, modified: statSync(join(root, name)).mtimeMs }))
47
+ .sort((a, b) => b.modified - a.modified);
48
+ for (const file of previous.slice(RETAINED_CONTEXTS - 1)) unlinkSync(join(root, file.name));
49
+ return { context_ref, prepared_at };
50
+ }
51
+
52
+ function record(value: unknown): value is Record<string, unknown> {
53
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
54
+ }
55
+
56
+ /** Retrieve one exact preparation under the active account without running synchronization again. */
57
+ export function readStartupContext(
58
+ workspace: string,
59
+ profile: Pick<AuthProfile, 'apiKey'>,
60
+ requestedRef?: string,
61
+ ): StoredContext {
62
+ let ref = requestedRef;
63
+ if (ref === undefined) {
64
+ try { ref = readFileSync(join(directory(workspace, profile), 'latest'), 'utf8').trim(); }
65
+ catch { throw new Error('No prepared context for this account. Run ccl prepare before ccl load.'); }
66
+ }
67
+ if (!REF.test(ref)) throw new Error('Invalid startup context reference. Use the context_ref returned by ccl prepare.');
68
+ let value: unknown;
69
+ try { value = JSON.parse(readFileSync(join(directory(workspace, profile), `${ref}.json`), 'utf8')); }
70
+ catch { throw new Error('Startup context is unavailable for this account. Do not repeat start/join; retain already received context and report the missing reference.'); }
71
+ if (!record(value) || value.schema !== SCHEMA || value.context_ref !== ref
72
+ || typeof value.prepared_at !== 'string' || typeof value.persona_available !== 'boolean'
73
+ || !record(value.sync) || !record(value.capabilities)
74
+ || (value.changes !== undefined && !record(value.changes))
75
+ || !Array.isArray(value.configuration_warnings) || !value.configuration_warnings.every(record)) {
76
+ throw new Error('Invalid stored startup context. Do not repeat start/join.');
77
+ }
78
+ return {
79
+ schema: SCHEMA, context_ref: ref, prepared_at: value.prepared_at,
80
+ sync: value.sync, capabilities: value.capabilities,
81
+ ...(value.changes ? { changes: value.changes } : {}),
82
+ configuration_warnings: value.configuration_warnings,
83
+ persona_available: value.persona_available,
84
+ };
85
+ }
@@ -0,0 +1,47 @@
1
+ import type { CapabilityWorkspaceType } from './capability-workspace.js';
2
+
3
+ interface ResourceChoice {
4
+ type: CapabilityWorkspaceType;
5
+ id: string;
6
+ selection_ref: string;
7
+ }
8
+
9
+ interface ContentConflict {
10
+ type: CapabilityWorkspaceType;
11
+ id: string;
12
+ resource_id: string;
13
+ selection_ref?: string;
14
+ }
15
+
16
+ interface SyncFailure {
17
+ type: CapabilityWorkspaceType;
18
+ id: string;
19
+ action: string;
20
+ code?: string;
21
+ }
22
+
23
+ export type StartupBlocker =
24
+ | ({ code: 'CAPABILITY_SELECTION_REQUIRED' } & ResourceChoice)
25
+ | ({ code: 'CAPABILITY_CONTENT_CONFLICT' } & ContentConflict)
26
+ | { code: 'SKILL_NAME_CONFLICT'; type: CapabilityWorkspaceType; id: string };
27
+
28
+ /** Preserve resource choices that must be handled before starting, including personas. */
29
+ export function summarizeStartupBlockers(
30
+ selections: readonly ResourceChoice[],
31
+ conflicts: readonly ContentConflict[],
32
+ failures: readonly SyncFailure[],
33
+ ): { blockers: StartupBlocker[] } {
34
+ return {
35
+ blockers: [
36
+ ...selections.map(({ type, id, selection_ref }): StartupBlocker => ({
37
+ code: 'CAPABILITY_SELECTION_REQUIRED', type, id, selection_ref,
38
+ })),
39
+ ...conflicts.map(({ type, id, resource_id, selection_ref }): StartupBlocker => ({
40
+ code: 'CAPABILITY_CONTENT_CONFLICT', type, id, resource_id,
41
+ ...(selection_ref ? { selection_ref } : {}),
42
+ })),
43
+ ...failures.filter(value => value.action === 'equipment' && value.code === 'SKILL_NAME_CONFLICT')
44
+ .map(({ type, id }): StartupBlocker => ({ code: 'SKILL_NAME_CONFLICT', type, id })),
45
+ ],
46
+ };
47
+ }
@@ -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,7 +1,7 @@
1
1
  import { basename } from 'node:path';
2
2
 
3
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;
4
+ export const PACKAGE_MANAGED_SKILL_NAMES = ['clawclaw', 'clawclaw-creator', 'clawclaw-start'] as const;
5
5
 
6
6
  export function reservedSkillName(name: string | null, directory?: string): string | undefined {
7
7
  const key = name?.trim().toLowerCase();
@@ -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,
@@ -69,7 +69,7 @@ export function skillNameConflicts(candidates: readonly SkillNameCandidate[]): S
69
69
  }
70
70
  return [...groups].filter(([, group]) => group.length > 1).map(([name, group]) => ({
71
71
  code: 'SKILL_NAME_CONFLICT', name, blocking: true, candidates: group,
72
- hint: 'Only one Skill with this name may be equipped. Choose which resource to keep and unequip the others using their selection_ref (or in Hub), then run ccl load. No Skill is renamed or replaced automatically.',
72
+ hint: 'Only one Skill with this name may be equipped. Choose which resource to keep and unequip the others using their selection_ref (or in Hub), then run ccl prepare. No Skill is renamed or replaced automatically.',
73
73
  }));
74
74
  }
75
75
 
@@ -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
@@ -311,7 +312,7 @@ export const LOCAL_LIFECYCLE_EVENT_HINT_FORMATTERS: Readonly<Record<string, Even
311
312
  case 'COMPETITION_NOT_OPEN':
312
313
  return 'Tell the user competition is not open now and use `competition.daily_windows` for the opening windows. Do not start normal matchmaking unless the user asks.';
313
314
  case 'ALREADY_IN_GAME':
314
- return 'Tell the user this account is already in a game. Run `ccl load` to confirm the existing participation, then attach with `ccl join` instead of starting another match.';
315
+ return 'Tell the user this account is already in a game. Run `ccl prepare` to confirm the existing participation, then attach with `ccl join` instead of starting another match.';
315
316
  default:
316
317
  return 'Tell the user competition matchmaking failed. Do not start normal matchmaking unless the user asks.';
317
318
  }
@@ -355,7 +356,7 @@ export const LOCAL_LIFECYCLE_EVENT_HINT_FORMATTERS: Readonly<Record<string, Even
355
356
  : 'The user left this game from the web page. Stop playing and do not start another match unless the user asks.'
356
357
  ),
357
358
  room_lobby_reconnect_failed: () => (
358
- 'The room round ended, but Lobby reattachment failed and this runtime is exiting. Ask whether to recover or leave the room; to recover, run `ccl load` and, if participation still exists, attach with `ccl join`. Do not start normal matchmaking.'
359
+ 'The room round ended, but Lobby reattachment failed and this runtime is exiting. Ask whether to recover or leave the room; to recover, run `ccl prepare` and, if participation still exists, attach with `ccl join`. Do not start normal matchmaking.'
359
360
  ),
360
361
  room_lobby_missing: () => (
361
362
  'The room round ended and the account is no longer in the familiar room. Do not start normal matchmaking; ask the user what to do next.'
@@ -15,7 +15,7 @@ export function shouldSkipAutoUpgrade(packageVersion = readPackageVersion()): bo
15
15
  return Boolean(packageVersion?.includes('-'));
16
16
  }
17
17
 
18
- /** Run during `ccl load`, before game start and event streaming begin. */
18
+ /** Run during `ccl prepare` (formerly load), before game start and event streaming begin. */
19
19
  export function runAutoUpgradeOnLoad(options?: { packageVersion?: string; notify?: (message: string) => void }): void {
20
20
  if (shouldSkipAutoUpgrade(options?.packageVersion)) return;
21
21
 
@@ -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.';
@@ -562,6 +562,8 @@ export async function runClawclawOwner(
562
562
  },
563
563
  });
564
564
  closeGameSyncTransports = () => client.closeGameSyncTransports();
565
+ // Validate before starting a participation or attaching any game transport.
566
+ void client.lobbyHostContext;
565
567
  const workspaceDir = getWorkspaceDir();
566
568
  ensureAccountUserDataLayout(workspaceDir, options.profile);
567
569
  const perceptionConfig = readWorkspacePerceptionConfig();
@@ -778,7 +780,6 @@ export async function runClawclawOwner(
778
780
  cclEventsMailbox = new AgentMailboxCoordinator({
779
781
  repository: mailboxRepository,
780
782
  readyView: () => runtime!.readReadyView(0, 1),
781
- onDelivered: (events) => perceptionReportAdapter.reportDelivered(events),
782
783
  presentEvent: ownerAgentEventPresenter('ccl_events', !!options.desktopEvents),
783
784
  compactState: compactStateForEvents,
784
785
  admitEvent: isClawclawAgentNotification,
@@ -813,7 +814,6 @@ export async function runClawclawOwner(
813
814
  admitEvent: isClawclawAgentNotification,
814
815
  repository: mailboxRepository,
815
816
  readyView: () => runtime!.readReadyView(0, 1),
816
- onDelivered: (events) => perceptionReportAdapter.reportDelivered(events),
817
817
  presentEvent: ownerAgentEventPresenter('desktop_ipc', true),
818
818
  compactState: () => null,
819
819
  consumerId: DESKTOP_IPC_MAILBOX_CONSUMER_ID,
@@ -871,7 +871,6 @@ export async function runClawclawOwner(
871
871
  if (channelPolicy.enabled) {
872
872
  channelAdapter = new ClaudeChannelMailboxAdapter({
873
873
  notificationOnly: true,
874
- onDelivered: (events) => perceptionReportAdapter.reportDelivered(events),
875
874
  repository: mailboxRepository,
876
875
  readyView: () => runtime!.readReadyView(0, 1),
877
876
  diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes),
@@ -959,10 +958,6 @@ export async function runClawclawOwner(
959
958
  mailboxRepository,
960
959
  'short',
961
960
  MONITOR_MAILBOX_CONSUMER_ID,
962
- undefined,
963
- (eventIds) => {
964
- perceptionReportAdapter.reportDelivered(mailboxService!.monitorDeliveredEvents(eventIds));
965
- },
966
961
  );
967
962
  relayAbort = new AbortController();
968
963
  relayAlive = true;
@@ -43,7 +43,7 @@ function uuidForEvent(event: CanonicalEvent): string {
43
43
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
44
44
  }
45
45
 
46
- /** Best-effort Mailbox fan-out to the active GameSync connection. */
46
+ /** Best-effort reporting of newly committed perceptions, independent of Agent delivery. */
47
47
  export class GameSyncPerceptionReportAdapter implements ClawclawMailboxDriver {
48
48
  readonly adapter: ClawclawMailboxAdapterDescriptor = {
49
49
  id: 'clawclaw.mailbox.adapter.game-sync-perception-report',
@@ -56,8 +56,8 @@ export class GameSyncPerceptionReportAdapter implements ClawclawMailboxDriver {
56
56
 
57
57
  constructor(private readonly options: GameSyncPerceptionReportAdapterOptions) {}
58
58
 
59
- /** Called only at Agent delivery, including Monitor backlog notification. */
60
- reportDelivered(events: readonly CanonicalEvent[]): void {
59
+ /** Mailbox calls this after the producing epoch's Ready boundary is committed. */
60
+ observeEvents(events: readonly CanonicalEvent[]): void {
61
61
  if (this.stopped) return;
62
62
  let skipped = 0;
63
63
  const reports: GameSyncPerceptionReport[] = [];