@myclaw163/clawclaw-cli 0.10.1 → 0.10.3

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 (48) hide show
  1. package/QUICKSTART.md +1 -1
  2. package/QUICKSTART_OTHER.md +8 -7
  3. package/docs/configuration.md +2 -2
  4. package/docs/custom-modules/skill.md +12 -10
  5. package/docs/runtime/agent-notifications.md +11 -0
  6. package/docs/user-guide/skill.md +12 -10
  7. package/package.json +2 -2
  8. package/scripts/check-skill-command-surface.mjs +12 -10
  9. package/scripts/enable_ccl_permissions.cjs +4 -0
  10. package/scripts/postinstall.mjs +1 -1
  11. package/scripts/sync-bundled-skill.mjs +35 -28
  12. package/skills/clawclaw/SKILL.md +8 -12
  13. package/skills/clawclaw/references/BEHAVIORS.md +5 -14
  14. package/skills/clawclaw/references/COMMANDS.md +3 -3
  15. package/skills/clawclaw/references/HUB.md +1 -1
  16. package/skills/clawclaw-creator/SKILL.md +82 -0
  17. package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +2 -2
  18. package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-MODULES.md +3 -1
  19. package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +1 -1
  20. package/skills/clawclaw-creator/references/CUSTOM-PERSONA-DEVELOPMENT.md +38 -0
  21. package/skills/clawclaw-creator/references/CUSTOM-SKILL-DEVELOPMENT.md +69 -0
  22. package/skills/clawclaw-creator/references/SYNC-AND-REPORT.md +36 -0
  23. package/src/commands/capability.ts +14 -11
  24. package/src/commands/load.ts +2 -1
  25. package/src/commands/skill.ts +34 -29
  26. package/src/commands/upgrade.ts +2 -2
  27. package/src/lib/agent-workspace-skills.ts +20 -13
  28. package/src/lib/capability-cloud-sync.ts +2 -1
  29. package/src/lib/capability-discovery.ts +2 -1
  30. package/src/lib/capability-workspace.ts +2 -1
  31. package/src/lib/game-client.ts +7 -1
  32. package/src/lib/package-skills.ts +4 -0
  33. package/src/lib/skill-host.ts +1 -1
  34. package/src/runtime/clawclaw/owner.ts +29 -5
  35. package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +3 -1
  36. package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-perception-report-adapter.ts +15 -20
  37. package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-runtime-report-adapter.ts +59 -0
  38. package/src/runtime/clawclaw/plugins/mailbox/index.ts +1 -0
  39. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +7 -1
  40. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +8 -4
  41. package/src/runtime/clawclaw/plugins/perception/report-content.ts +50 -0
  42. package/src/runtime/game-sync-ingress-protocol.ts +3 -2
  43. package/src/runtime/game-sync-ingress-worker.ts +7 -1
  44. package/src/runtime/game-sync-protocol.ts +64 -4
  45. package/src/runtime/threaded-ws-client.ts +11 -2
  46. package/src/runtime/ws-client.ts +6 -0
  47. package/skills/clawclaw/references/CUSTOM-SKILL-DEVELOPMENT.md +0 -67
  48. /package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-MODULE-API.md +0 -0
@@ -1,3 +1,4 @@
1
+ import { isPackageManagedSkill } from './package-skills.js';
1
2
  import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
2
3
  import { join } from 'node:path';
3
4
  import type { AuthProfile } from './auth.js';
@@ -82,7 +83,7 @@ export function discoverLocalCapabilities(
82
83
  return [];
83
84
  }
84
85
  const name = readSkillName(path);
85
- return name && name !== 'clawclaw' ? [registerDiscoveredCapability(workspaceDir, profile, {
86
+ return name && !isPackageManagedSkill(name) ? [registerDiscoveredCapability(workspaceDir, profile, {
86
87
  type: 'skill',
87
88
  path,
88
89
  runtimeId: name,
@@ -1,3 +1,4 @@
1
+ import { isPackageManagedSkill } from './package-skills.js';
1
2
  import {
2
3
  cpSync,
3
4
  existsSync,
@@ -317,7 +318,7 @@ export function pendingCapabilitySelections(
317
318
  ): readonly CapabilityWorkspaceEntry[] {
318
319
  return Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
319
320
  .filter((entry) => entry.origin === 'local' && entry.selection === 'pending'
320
- && !(entry.type === 'skill' && entry.runtimeId === 'clawclaw'))
321
+ && !(entry.type === 'skill' && isPackageManagedSkill(entry.runtimeId)))
321
322
  .sort((left, right) => left.discoveredAt.localeCompare(right.discoveredAt));
322
323
  }
323
324
 
@@ -14,7 +14,7 @@ import {
14
14
  import { RuntimeLogger } from '../runtime/runtime-logger.js';
15
15
  import { ThreadedWsClient, type ThreadedWsClientConfig } from '../runtime/threaded-ws-client.js';
16
16
  import type { RawWsMessageSink } from '../runtime/raw-ws-log.js';
17
- import type { GameSyncPerceptionReport } from '../runtime/game-sync-protocol.js';
17
+ import type { GameSyncPerceptionReport, GameSyncRuntimeReport } from '../runtime/game-sync-protocol.js';
18
18
  import type { QueueMode } from './competition.js';
19
19
  import type {
20
20
  CreateRoomOptions,
@@ -527,6 +527,12 @@ export class GameClient {
527
527
  return this.ws?.reportPerceptions(perceptions) ?? false;
528
528
  }
529
529
 
530
+ /** A report must still belong to the Source-accepted game/connection it describes. */
531
+ reportGameSyncRuntime(report: GameSyncRuntimeReport, gameId: string, connectionId: string): boolean {
532
+ if (this.ws?.connectionId !== connectionId || this.ws?.resumeState?.gameId !== gameId) return false;
533
+ return this.ws.reportRuntime(report);
534
+ }
535
+
530
536
  get gameSyncLocale(): 'zh-CN' | 'en-US' {
531
537
  return this.ws?.resumeState?.locale ?? this.gameSyncResumeState?.locale ?? 'zh-CN';
532
538
  }
@@ -0,0 +1,4 @@
1
+ /** Package-owned teaching skills are independent of an account's Hub loadout. */
2
+ export function isPackageManagedSkill(name: string | null): boolean {
3
+ return name === 'clawclaw' || name === 'clawclaw-creator';
4
+ }
@@ -244,6 +244,6 @@ export interface SkillHostSkip {
244
244
  export function skillHostSkip(name: string, paths: string[]): SkillHostSkip {
245
245
  return {
246
246
  name, reason: 'local_skill_directory_exists', paths, blocking: false,
247
- message: 'Same-name local Skill paths were preserved. CCL Skill linking was skipped; gameplay may continue. The Agent host may still load the local Skill.',
247
+ message: 'Same-name local Skill paths were preserved. CCL Skill link changes were skipped only at the listed paths; other host paths are handled independently. Gameplay may continue. The affected Agent hosts may still load their local Skill.',
248
248
  };
249
249
  }
@@ -85,6 +85,7 @@ import {
85
85
  ClaudeChannelSocketSink,
86
86
  DesktopEventSocketSink,
87
87
  GameSyncPerceptionReportAdapter,
88
+ GameSyncRuntimeReportAdapter,
88
89
  AgentMailboxCoordinator,
89
90
  clawclawEventRequiresDetails,
90
91
  MailboxEventBatchPump,
@@ -735,15 +736,36 @@ export async function runClawclawOwner(
735
736
  throw new Error('The configured Runtime repository does not support durable Mailbox delivery.');
736
737
  }
737
738
  const mailboxRepository = runtime.repository;
739
+ const perceptionSourceById = new Map(perceptionSources.map(source => [source.id, source]));
738
740
  const perceptionReportAdapter = new GameSyncPerceptionReportAdapter({
739
- producerPluginId: assembly.perception.id,
740
- descriptor: (eventType) => assembly.perception.localizedModuleDescriptorForEvent(
741
- eventType,
742
- client.gameSyncLocale,
743
- ),
741
+ producerPluginIds: [assembly.perception.id, assembly.reminders.id, ...(assembly.modules ? [assembly.modules.id] : [])],
742
+ descriptor: id => {
743
+ const source = perceptionSourceById.get(id);
744
+ return source ? { ...resolveClawclawResourceMetadata({ ...source.manifest, display: source.display }, client.gameSyncLocale), perceptionId: id } : undefined;
745
+ },
744
746
  send: (reports) => client.reportGameSyncPerceptions(reports),
745
747
  diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes),
746
748
  });
749
+ const runtimeReportAdapter = new GameSyncRuntimeReportAdapter({
750
+ snapshot: ready => {
751
+ const view = runtime!.readReadyView(0, 1);
752
+ if (view.epochSeq !== ready.epochSeq || view.scope.segmentId !== ready.scope.segmentId) return null;
753
+ const state = view.state.state;
754
+ const status = view.state.stateStatus;
755
+ if (!state?.game_id || status.connectionState !== 'connected' || !status.connectionId
756
+ || status.terminal || state.phase === 'game_over' || state.phase === 'settling') return null;
757
+ const locale = client.gameSyncLocale;
758
+ return { gameId: String(state.game_id), connectionId: status.connectionId, resources: {
759
+ perceivers: [...assembly.perception.localizedModuleDescriptors(locale),
760
+ ...assembly.reminders.localizedModuleDescriptors(locale),
761
+ ...(assembly.modules?.localizedModuleDescriptors(locale) ?? [])].sort((a, b) => a.id.localeCompare(b.id)),
762
+ strategies: behaviorCatalog.list().filter(entry => entry.loadable).map(entry =>
763
+ resolveClawclawResourceMetadata(behaviorSourceById.get(entry.id)!, locale)).sort((a, b) => a.id.localeCompare(b.id)),
764
+ } };
765
+ },
766
+ send: (report, gameId, connectionId) => client.reportGameSyncRuntime(report, gameId, connectionId),
767
+ diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes),
768
+ });
747
769
  cclEventsMailbox = new AgentMailboxCoordinator({
748
770
  repository: mailboxRepository,
749
771
  readyView: () => runtime!.readReadyView(0, 1),
@@ -772,6 +794,8 @@ export async function runClawclawOwner(
772
794
  diagnostic: (name, attributes, severity) => runtime?.diagnostic(name, attributes, severity),
773
795
  });
774
796
  const mailboxDrivers: ClawclawMailboxDriver[] = [
797
+ runtimeReportAdapter,
798
+ perceptionReportAdapter,
775
799
  mailboxService,
776
800
  cclEventsMailbox,
777
801
  ];
@@ -1,4 +1,5 @@
1
1
  import { prepareNotificationContent } from '../perception/notification-content.js';
2
+ import { preparePerceptionNotification } from '../perception/report-content.js';
2
3
  import { isNotificationTurn } from '../../notification-turn.js';
3
4
  import type { RuntimeEpochPlugin, RuntimeEpochPluginContext, RuntimeEpochPluginInput, RuntimeEpochPluginResult } from '../../../framework/plugins/index.js';
4
5
  import type { RuntimeEventProposal } from '../../../framework/plugins/index.js';
@@ -138,6 +139,7 @@ export class ClawclawReminderPlugin implements RuntimeEpochPlugin<Record<string,
138
139
  keys.add(event.key);
139
140
  accepted.push({ type: event.type, dedupeKey: JSON.stringify([selected.id, event.key]),
140
141
  dedupeScope: 'segment', wakeAgent: event.wakeAgent, payload: { ...event.payload },
142
+ notificationContent: preparePerceptionNotification(event.type, event.payload, game, selected.id, input.frame.backendTick),
141
143
  occurredAt: new Date(moduleInput.nowMs).toISOString() });
142
144
  }
143
145
  // Task snapshots establish baselines. Fresh speech remains an occurrence
@@ -150,7 +152,7 @@ export class ClawclawReminderPlugin implements RuntimeEpochPlugin<Record<string,
150
152
  events.push(...outputs.flat());
151
153
  this.checkpoint = next;
152
154
  return { outcome: 'processed', events: events.map(event => ({ ...event,
153
- notificationContent: prepareNotificationContent(event.type, event.payload, game, 'custom') })), checkpoint: next,
155
+ notificationContent: event.notificationContent ?? prepareNotificationContent(event.type, event.payload, game, 'custom') })), checkpoint: next,
154
156
  ...(input.pendingEvents.length ? { consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq } : {}) };
155
157
  }
156
158
  private markFailed(topic: ReminderTopic, context: RuntimeEpochPluginContext<Record<string, any>>, error: unknown): void {
@@ -1,4 +1,6 @@
1
1
  import { createHash } from 'node:crypto';
2
+ import { PERCEPTION_REPORT_VIEW, type PerceptionReportContent } from '../../perception/report-content.js';
3
+ import { gameSyncPerceptionReportMessage } from '../../../../game-sync-protocol.js';
2
4
  import type { GameSyncPerceptionReport } from '../../../../game-sync-protocol.js';
3
5
  import type { CanonicalEvent } from '../../../../framework/events/index.js';
4
6
  import type {
@@ -19,8 +21,8 @@ export interface GameSyncPerceptionDescriptor {
19
21
 
20
22
  export interface GameSyncPerceptionReportAdapterOptions {
21
23
  readonly send: (reports: readonly GameSyncPerceptionReport[]) => boolean;
22
- readonly descriptor: (eventType: string) => GameSyncPerceptionDescriptor | undefined;
23
- readonly producerPluginId: string;
24
+ readonly descriptor: (perceiverId: string) => GameSyncPerceptionDescriptor | undefined;
25
+ readonly producerPluginIds: readonly string[];
24
26
  readonly diagnostic?: (
25
27
  name: string,
26
28
  attributes?: Readonly<Record<string, unknown>>,
@@ -41,13 +43,6 @@ function uuidForEvent(event: CanonicalEvent): string {
41
43
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
42
44
  }
43
45
 
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
46
  /** Best-effort Mailbox fan-out to the active GameSync connection. */
52
47
  export class GameSyncPerceptionReportAdapter implements ClawclawMailboxDriver {
53
48
  readonly adapter: ClawclawMailboxAdapterDescriptor = {
@@ -73,23 +68,23 @@ export class GameSyncPerceptionReportAdapter implements ClawclawMailboxDriver {
73
68
  }
74
69
  if (this.reported.has(event.eventId)) continue;
75
70
  if (
76
- event.producerPluginId !== this.options.producerPluginId
71
+ !event.producerPluginId || !this.options.producerPluginIds.includes(event.producerPluginId)
77
72
  || event.deliveryClass === 'internal_only'
78
73
  ) continue;
79
- const descriptor = this.options.descriptor(event.type);
80
- const output = typeof event.payload.text === 'string' ? event.payload.text.trim() : '';
81
- const tick = sourceTick(event);
82
- if (!descriptor || !descriptor.name.trim() || !output || tick === undefined) {
74
+ const content = event.notificationContent?.views?.[PERCEPTION_REPORT_VIEW] as PerceptionReportContent | undefined;
75
+ const descriptor = content && this.options.descriptor(content.perceiver_id);
76
+ if (!content || !descriptor || !descriptor.name.trim() || !content.output) {
83
77
  skipped += 1;
84
78
  continue;
85
79
  }
80
+ let report: GameSyncPerceptionReport;
81
+ try {
82
+ report = gameSyncPerceptionReportMessage([{
83
+ ...content, id: uuidForEvent(event), name: descriptor.name.trim(),
84
+ }]).data.perceptions[0]!;
85
+ } catch { skipped += 1; continue; }
86
86
  this.reported.add(event.eventId);
87
- reports.push({
88
- id: uuidForEvent(event),
89
- name: descriptor.name.trim(),
90
- output,
91
- source_tick: tick,
92
- });
87
+ reports.push(report);
93
88
  }
94
89
  if (skipped > 0) {
95
90
  this.options.diagnostic?.('runtime.mailbox.perception_report_skipped', {
@@ -0,0 +1,59 @@
1
+ import { gameSyncRuntimeReportMessage, type GameSyncRuntimeReport } from '../../../../game-sync-protocol.js';
2
+ import type { RuntimeEpochReady } from '../../../../framework/plugins/index.js';
3
+ import type { ClawclawMailboxDriver } from '../mailbox-plugin.js';
4
+
5
+ export interface GameSyncRuntimeReportBoundary {
6
+ readonly gameId: string;
7
+ readonly connectionId: string;
8
+ readonly resources: GameSyncRuntimeReport;
9
+ }
10
+
11
+ /** Latest complete resource snapshot; no delivery ACK, gameplay events, or computation backpressure. */
12
+ export class GameSyncRuntimeReportAdapter implements ClawclawMailboxDriver {
13
+ readonly adapter = { id: 'clawclaw.mailbox.adapter.game-sync-runtime-report', acknowledgement: 'none' } as const;
14
+ private stopped = false;
15
+ private queued = false;
16
+ private lastSent?: string;
17
+ private lastInvalid?: string;
18
+ private ready?: RuntimeEpochReady;
19
+
20
+ constructor(private readonly options: {
21
+ snapshot: (ready: RuntimeEpochReady) => GameSyncRuntimeReportBoundary | null;
22
+ send: (report: GameSyncRuntimeReport, gameId: string, connectionId: string) => boolean;
23
+ diagnostic?: (name: string, attributes: Record<string, unknown>) => void;
24
+ }) {}
25
+
26
+ afterReady(ready: RuntimeEpochReady): void {
27
+ if (this.stopped) return;
28
+ this.ready = ready;
29
+ if (this.queued) return;
30
+ this.queued = true;
31
+ queueMicrotask(() => { this.queued = false; void this.flush(); });
32
+ }
33
+
34
+ async flush(): Promise<void> {
35
+ if (this.stopped || !this.ready) return;
36
+ try {
37
+ const boundary = this.options.snapshot(this.ready);
38
+ if (!boundary) return;
39
+ const key = JSON.stringify([boundary.gameId, boundary.connectionId, boundary.resources]);
40
+ if (key === this.lastSent || key === this.lastInvalid) return;
41
+ let report: GameSyncRuntimeReport;
42
+ try { report = gameSyncRuntimeReportMessage(boundary.resources).data; }
43
+ catch (error) {
44
+ this.lastInvalid = key;
45
+ this.options.diagnostic?.('runtime.mailbox.runtime_report_invalid', {
46
+ error: error instanceof Error ? error.message : String(error),
47
+ });
48
+ return;
49
+ }
50
+ if (this.options.send(report, boundary.gameId, boundary.connectionId)) this.lastSent = key;
51
+ } catch (error) {
52
+ this.options.diagnostic?.('runtime.mailbox.runtime_report_failed', {
53
+ error: error instanceof Error ? error.message : String(error),
54
+ });
55
+ }
56
+ }
57
+
58
+ async stop(): Promise<void> { this.stopped = true; this.ready = undefined; }
59
+ }
@@ -2,6 +2,7 @@ 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
4
  export * from './adapters/game-sync-perception-report-adapter.js';
5
+ export * from './adapters/game-sync-runtime-report-adapter.js';
5
6
  export * from './consumer-ids.js';
6
7
  export * from './desktop-event-socket.js';
7
8
  export * from './mailbox-event-batch-delivery.js';
@@ -1,5 +1,6 @@
1
1
  import { normalizePerceptionStrategyNames } from '../../perception-strategy-names.js';
2
2
  import { prepareNotificationContent } from './notification-content.js';
3
+ import { preparePerceptionNotification } from './report-content.js';
3
4
  import { isNotificationTurn } from '../../notification-turn.js';
4
5
  import type { RuntimeEpochPluginInput } from '../../../framework/plugins/index.js';
5
6
  import { normalizeBehaviorInput } from '../../behavior-input-fields.js';
@@ -122,7 +123,12 @@ function createAdapter(options: PerceptionModulePluginOptions): PerceptionAdapte
122
123
  return { invocation: { scope: moduleInput.scope, value: moduleInput }, inputState: comparison.baseline,
123
124
  evaluate: !!frame || !!clawclawComputationGameState(input.frame.state) || moduleInput.events.length > 0 };
124
125
  },
125
- notification: (event, prepared) => prepareNotificationContent(event.type, event.payload, (prepared.value as Prepared).game, 'custom'),
126
+ notification: (event, prepared, source) => {
127
+ const { game, input } = prepared.value as Prepared;
128
+ return source
129
+ ? preparePerceptionNotification(event.type, event.payload, game, source.id, input.frame.backendTick)
130
+ : prepareNotificationContent(event.type, event.payload, game, 'custom');
131
+ },
126
132
  };
127
133
  }
128
134
  export class ClawclawPerceptionModulePlugin extends PerceptionHost {
@@ -1,4 +1,5 @@
1
1
  import { prepareNotificationContent } from './notification-content.js';
2
+ import { preparePerceptionNotification } from './report-content.js';
2
3
  import { isNotificationTurn } from '../../notification-turn.js';
3
4
  import type {
4
5
  RuntimeEpochFlushReason,
@@ -556,7 +557,7 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
556
557
  outcome: 'processed',
557
558
  ...(inspected.reason ? { reason: inspected.reason } : {}),
558
559
  events: inspected.proposals.map(event => ({ ...event,
559
- notificationContent: prepareNotificationContent(event.type, event.payload, input.currentState.state, 'custom') })),
560
+ notificationContent: event.notificationContent ?? prepareNotificationContent(event.type, event.payload, input.currentState.state, 'custom') })),
560
561
  checkpoint,
561
562
  }
562
563
  : { outcome: 'noop', reason: inspected.reason ?? 'not_visual_state', checkpoint };
@@ -1447,9 +1448,12 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
1447
1448
  const values = proposals(result.value);
1448
1449
  // Aliased copies may emit the same source-level dedupe key. Keep their
1449
1450
  // outputs separate without renaming any public Event type or payload.
1450
- return module.source?.declaredId && module.source.declaredId !== module.manifest.id
1451
- ? values.map(value => ({ ...value, dedupeKey: `ccl-alias:${JSON.stringify([module.manifest.id, value.dedupeKey])}` }))
1452
- : values;
1451
+ return values.map(value => ({ ...value,
1452
+ ...(module.source?.declaredId && module.source.declaredId !== module.manifest.id
1453
+ ? { dedupeKey: `ccl-alias:${JSON.stringify([module.manifest.id, value.dedupeKey])}` } : {}),
1454
+ notificationContent: preparePerceptionNotification(value.type, value.payload,
1455
+ this.lastVisualFrame?.gameState ?? null, module.manifest.id, this.lastVisualTick),
1456
+ }));
1453
1457
  });
1454
1458
  }
1455
1459
 
@@ -0,0 +1,50 @@
1
+ import type { EventNotificationContent } from '../../../framework/events/types.js';
2
+ import type { GameSyncPerceptionTime } from '../../../game-sync-protocol.js';
3
+ import { timeRange } from '../../../../sdk/perception-plugin/math.js';
4
+ import { prepareNotificationContent } from './notification-content.js';
5
+
6
+ export const PERCEPTION_REPORT_VIEW = 'clawclaw.perception-report';
7
+ export type PerceptionReportContent = GameSyncPerceptionTime & {
8
+ readonly perceiver_id: string;
9
+ readonly output: string;
10
+ };
11
+
12
+ const isTick = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0;
13
+
14
+ /** Freeze the display projection at the producing module's accepted input boundary. */
15
+ export function preparePerceptionNotification(
16
+ type: string,
17
+ payload: Readonly<Record<string, unknown>>,
18
+ state: Record<string, any> | null,
19
+ perceiverId: string,
20
+ backendTick?: number | null,
21
+ ): EventNotificationContent {
22
+ const notification = prepareNotificationContent(type, payload, state, 'custom');
23
+ let output = typeof payload.text === 'string' ? payload.text.trim() : '';
24
+ if (!output) return notification;
25
+ const from = payload.from_source_tick ?? payload.from_tick;
26
+ const to = payload.to_source_tick ?? payload.to_tick;
27
+ let time: GameSyncPerceptionTime;
28
+ if (from !== undefined || to !== undefined) {
29
+ if (!isTick(from) || !isTick(to) || from > to || payload.source_tick !== undefined) return notification;
30
+ time = from === to ? { source_tick: to } : { from_source_tick: from, to_source_tick: to };
31
+ // Existing visual modules use this exact SDK formatter. Do not parse arbitrary prose for times.
32
+ if (type.startsWith('visual.')) {
33
+ const prefix = timeRange(from, to);
34
+ for (const separator of [',', ', ']) {
35
+ if (output.startsWith(prefix + separator)) {
36
+ output = output.slice(prefix.length + separator.length).trim();
37
+ break;
38
+ }
39
+ }
40
+ }
41
+ } else {
42
+ const tick = payload.source_tick ?? payload.tick ?? backendTick;
43
+ if (!isTick(tick)) return notification;
44
+ time = { source_tick: tick };
45
+ }
46
+ if (output) notification.views = { [PERCEPTION_REPORT_VIEW]: {
47
+ perceiver_id: perceiverId, output, ...time,
48
+ } satisfies PerceptionReportContent };
49
+ return notification;
50
+ }
@@ -1,4 +1,4 @@
1
- import type { GameSyncPerceptionReport } from './game-sync-protocol.js';
1
+ import type { GameSyncPerceptionReport, GameSyncRuntimeReport } from './game-sync-protocol.js';
2
2
  import type { BufferedRawWsLogOptions, RawWsLogStats } from './raw-ws-log.js';
3
3
  import type { WsConnectionState } from '../sdk/types.js';
4
4
  import type { GameSyncResumeState, WsCloseInfo, WsInputFrame, WsProtocolErrorInfo, WsRecoveryStartedInfo } from './ws-client.js';
@@ -17,7 +17,8 @@ export interface GameSyncIngressConfig {
17
17
 
18
18
  export type IngressCommand =
19
19
  | { type: 'consumed'; token: string }
20
- | { type: 'report'; perceptions: readonly GameSyncPerceptionReport[] }
20
+ | { type: 'report'; perceptions: readonly GameSyncPerceptionReport[]; connectionId: string }
21
+ | { type: 'runtime_report'; report: GameSyncRuntimeReport; connectionId: string }
21
22
  | { type: 'telemetry_ack' }
22
23
  | { type: 'stop' };
23
24
 
@@ -248,7 +248,13 @@ port.on('message', (message: IngressCommand) => {
248
248
  pump();
249
249
  reconnectWhenDrained();
250
250
  } else if (message.type === 'report') {
251
- try { client.reportPerceptions(message.perceptions); } finally { post({ type: 'report_done' }); }
251
+ try {
252
+ if (message.connectionId === client.connectionId) client.reportPerceptions(message.perceptions);
253
+ } finally { post({ type: 'report_done' }); }
254
+ } else if (message.type === 'runtime_report') {
255
+ try {
256
+ if (message.connectionId === client.connectionId) client.reportRuntime(message.report);
257
+ } finally { post({ type: 'report_done' }); }
252
258
  } else if (message.type === 'telemetry_ack') {
253
259
  telemetryPending = false;
254
260
  } else if (message.type === 'stop') {
@@ -31,11 +31,31 @@ export interface GameSyncErrorData {
31
31
  readonly message?: string;
32
32
  }
33
33
 
34
- export interface GameSyncPerceptionReport {
34
+ export type GameSyncPerceptionTime =
35
+ | { readonly source_tick: number; readonly from_source_tick?: never; readonly to_source_tick?: never }
36
+ | { readonly source_tick?: never; readonly from_source_tick: number; readonly to_source_tick: number };
37
+
38
+ export type GameSyncPerceptionReport = GameSyncPerceptionTime & {
35
39
  readonly id: string;
40
+ readonly perceiver_id?: string;
36
41
  readonly name: string;
37
42
  readonly output: string;
38
- readonly source_tick: number;
43
+ };
44
+
45
+ export interface GameSyncResourceInfo {
46
+ readonly id: string;
47
+ readonly name: string;
48
+ readonly description?: string;
49
+ }
50
+
51
+ export interface GameSyncRuntimeReport {
52
+ readonly perceivers?: readonly GameSyncResourceInfo[] | null;
53
+ readonly strategies?: readonly GameSyncResourceInfo[] | null;
54
+ }
55
+
56
+ export interface GameSyncRuntimeReportMessage {
57
+ readonly type: 'game.sync.runtime.report';
58
+ readonly data: GameSyncRuntimeReport;
39
59
  }
40
60
 
41
61
  export interface GameSyncPerceptionReportMessage {
@@ -87,6 +107,36 @@ function eventArray(value: unknown, field: string): Record<string, any>[] {
87
107
 
88
108
  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
109
 
110
+ function resourceId(value: unknown, field: string): string {
111
+ const id = nonEmptyString(value, field).trim();
112
+ if (!id || [...id].length > 128) throw new TypeError(`${field} must contain 1 to 128 characters`);
113
+ return id;
114
+ }
115
+
116
+ export function gameSyncRuntimeReportMessage(report: GameSyncRuntimeReport): GameSyncRuntimeReportMessage {
117
+ if (report.perceivers == null && report.strategies == null) {
118
+ throw new TypeError('GameSync runtime report requires perceivers or strategies');
119
+ }
120
+ const data: { perceivers?: GameSyncResourceInfo[] | null; strategies?: GameSyncResourceInfo[] | null } = {};
121
+ for (const key of ['perceivers', 'strategies'] as const) {
122
+ const list = report[key];
123
+ if (list === undefined) continue;
124
+ if (list === null) { data[key] = null; continue; }
125
+ if (!Array.isArray(list) || list.length > 50) throw new TypeError(`${key} must contain at most 50 resources`);
126
+ const ids = new Set<string>();
127
+ data[key] = list.map(item => {
128
+ const id = resourceId(item.id, `${key}.id`);
129
+ if (ids.has(id)) throw new TypeError(`${key} resource IDs must be unique`);
130
+ ids.add(id);
131
+ const name = nonEmptyString(item.name, `${key}.name`).trim();
132
+ if (!name) throw new TypeError(`${key}.name must not be blank`);
133
+ if (item.description !== undefined && typeof item.description !== 'string') throw new TypeError(`${key}.description must be a string`);
134
+ return { id, name, description: item.description?.trim() ?? '' };
135
+ });
136
+ }
137
+ return { type: 'game.sync.runtime.report', data };
138
+ }
139
+
90
140
  /** Build one client perception report frame using the backend's all-or-nothing validation rules. */
91
141
  export function gameSyncPerceptionReportMessage(
92
142
  perceptions: readonly GameSyncPerceptionReport[],
@@ -109,8 +159,18 @@ export function gameSyncPerceptionReportMessage(
109
159
  if (typeof perception.output !== 'string') {
110
160
  throw new TypeError(`GameSync perception report[${index}].output must be a string`);
111
161
  }
112
- integer(perception.source_tick, `GameSync perception report[${index}].source_tick`);
113
- return { ...perception };
162
+ const instant = perception.source_tick !== undefined;
163
+ const interval = perception.from_source_tick !== undefined || perception.to_source_tick !== undefined;
164
+ if (instant === interval) throw new TypeError('Perception report requires exactly one instantaneous or interval time');
165
+ if (instant) integer(perception.source_tick, `GameSync perception report[${index}].source_tick`);
166
+ else {
167
+ integer(perception.from_source_tick, `GameSync perception report[${index}].from_source_tick`);
168
+ integer(perception.to_source_tick, `GameSync perception report[${index}].to_source_tick`);
169
+ if (perception.from_source_tick! > perception.to_source_tick!) throw new TypeError('Perception report time interval is reversed');
170
+ }
171
+ return { ...perception, ...(perception.perceiver_id === undefined ? {} : {
172
+ perceiver_id: resourceId(perception.perceiver_id, `GameSync perception report[${index}].perceiver_id`),
173
+ }) };
114
174
  });
115
175
  return {
116
176
  type: 'game.sync.perception.report',
@@ -1,7 +1,7 @@
1
1
  import { Worker } from 'node:worker_threads';
2
2
  import { EventEmitter } from 'node:events';
3
3
  import { WsConnectionState } from '../sdk/types.js';
4
- import { gameSyncPerceptionReportMessage, type GameSyncPerceptionReport } from './game-sync-protocol.js';
4
+ import { gameSyncPerceptionReportMessage, gameSyncRuntimeReportMessage, type GameSyncPerceptionReport, type GameSyncRuntimeReport } from './game-sync-protocol.js';
5
5
  import type { GameSyncIngressConfig, IngressCommand, IngressEvent } from './game-sync-ingress-protocol.js';
6
6
  import type { GameSyncResumeState, WsClient, WsClientConfig, WsInputFrame, WsCloseInfo, WsProtocolErrorInfo, WsRecoveryStartedInfo } from './ws-client.js';
7
7
 
@@ -155,7 +155,16 @@ export class ThreadedWsClient implements Pick<WsClient, keyof WsClient> {
155
155
  const message = gameSyncPerceptionReportMessage(perceptions);
156
156
  if (Buffer.byteLength(JSON.stringify(message)) > 256 * 1024) return false;
157
157
  this.pendingReports++;
158
- this.post({ type: 'report', perceptions });
158
+ this.post({ type: 'report', perceptions: message.data.perceptions, connectionId: this.connectionId });
159
+ return true;
160
+ }
161
+
162
+ reportRuntime(report: GameSyncRuntimeReport): boolean {
163
+ if (!this.connected || this.stopped || this.pendingReports >= 16) return false;
164
+ const message = gameSyncRuntimeReportMessage(report);
165
+ if (Buffer.byteLength(JSON.stringify(message)) > 256 * 1024) return false;
166
+ this.pendingReports++;
167
+ this.post({ type: 'runtime_report', report: message.data, connectionId: this.connectionId });
159
168
  return true;
160
169
  }
161
170
 
@@ -13,6 +13,8 @@ import {
13
13
  parseGameSyncMessage,
14
14
  type GameSyncErrorData,
15
15
  type GameSyncPerceptionReport,
16
+ gameSyncRuntimeReportMessage,
17
+ type GameSyncRuntimeReport,
16
18
  } from './game-sync-protocol.js';
17
19
 
18
20
  export interface GameSyncResumeState {
@@ -194,6 +196,10 @@ export class WsClient {
194
196
  return this.send(gameSyncPerceptionReportMessage(perceptions));
195
197
  }
196
198
 
199
+ reportRuntime(report: GameSyncRuntimeReport): boolean {
200
+ return this.send(gameSyncRuntimeReportMessage(report));
201
+ }
202
+
197
203
  /**
198
204
  * Advance the resume/ACK watermark after the consumer has accepted the frame.
199
205
  * The threaded consumer retains it in memory before ACK; this is not a disk flush.
@@ -1,67 +0,0 @@
1
- # 自定义游戏技能
2
-
3
- 游戏技能(Skill)是供 Agent 阅读的操作说明与参考资料,例如会议记录方法、发言流程或阵营线索整理。它不是自动运行的策略或感知模块,也不会因为装配就获得新的游戏 API。持续动作决策使用策略,视觉事实识别使用感知;技能只能指导 Agent 使用当前可用的命令和信息。
4
-
5
- ## 本地创建与修改
6
-
7
- 新技能的实体目录放在当前账号的工作副本中:
8
-
9
- ```text
10
- <workspace>/user-data/accounts/<account-hash>/capabilities/skills/my-game-helper/
11
- SKILL.md
12
- references/
13
- examples.md
14
- scripts/
15
- helper.py
16
- ```
17
-
18
- 只有 `SKILL.md` 是必需的;附属目录按需创建。正文通过相对路径引用资料。脚本不是自动执行入口,必须说明用途、参数、依赖及何时运行。
19
-
20
- 先用 `ccl workspace` 确认工作目录。通过当前账号 `ccl strategy list` 或 `ccl perception --list` 返回的 `working_copy_path` 定位同一账号的 `capabilities` 根目录;已有技能也可用 `ccl capability list` 查看登记信息。不能把其他账号的目录当作当前账号,不能猜测 account-hash;没有可确认的账号路径时,先确认路径再写入。`ccl data path` 只返回总 user-data 目录,不是当前账号技能目录。
21
-
22
- 不要直接在 `.agents/skills`、`.claude/skills`、`.codex/skills` 或 `.openclaw/skills` 下创建游戏技能实体。这些宿主入口由 CCL 建立目录链接,指向账号工作副本。不要修改 Hub revision cache,也不要覆盖官方 `clawclaw` 技能。修改现有技能应找到原工作副本,不另建同名副本。
23
-
24
- 最小示例:
25
-
26
- ```markdown
27
- ---
28
- name: my-game-helper
29
- description: Organize visible meeting evidence before speaking.
30
- ---
31
-
32
- # 会议线索整理
33
-
34
- 当玩家要求整理会议线索时使用本技能。
35
- 只依据当前玩家已获得的状态、事件和发言,区分亲眼所见与他人陈述。
36
- 按“事实、来源、尚待确认的问题”整理要点;使用官方 ClawClaw 技能中当前支持的命令行动。
37
- 不要推断不可见身份,不要把动作请求当作执行成功。
38
- ```
39
-
40
- 目录名与 `name` 保持一致。使用唯一名称;名称以字母或数字开头,后续只使用字母、数字、点、下划线或连字符,总长度不超过 128 字符。不要使用保留名称 `clawclaw`。描述说明适用场景,正文写清执行步骤、信息边界和完成条件;不要复制过时的游戏命令、写入凭据或要求绕过官方开局流程。
41
-
42
- ## 本地装配
43
-
44
- 保存后运行 `ccl load`。首次发现纯本地技能时,按玩家选择执行其中一条:
45
-
46
- ```powershell
47
- ccl capability equip skill/my-game-helper
48
- ccl capability unequip skill/my-game-helper
49
- ```
50
-
51
- 之后重新完整运行 `ccl load`,依据最终结果继续游戏。已保存的选择无需反复询问。合法账号工作副本会参与 CCL 自动云端同步;未装配不等于不上传。尚不希望参与同步的草稿放在账号的 `drafts`,不要放进 `skills` 主目录。
52
-
53
- ## 网页导入与公开分享
54
-
55
- 网页导入是另一条独立路径,无需先放进本地账号目录:在当前账号的技能管理入口导入技能文件包,完成装配,再由同一账号执行 `ccl load`。文件包包含 `SKILL.md` 和所需附属文件;ZIP 可直接以 `SKILL.md` 为根,也可包含一层技能文件夹。
56
-
57
- 导入自己的配置、装配使用、上传至 HUB 广场公开分享是不同操作。公开分享按网页对应入口操作;不要把本地创建或自动同步描述成已经公开发布。
58
-
59
- ## 同名真实目录
60
-
61
- 如果任一宿主同名位置已存在真实目录,CCL 保留原文件,跳过该技能在所有宿主上的链接装配,并清理对应的既有 CCL 链接;不会迁移、覆盖或删除真实目录,也不会因此修改 Hub 装配选择。
62
-
63
- 命令以英文结构化提示返回 `reason: local_skill_directory_exists`、具体 `paths` 和 `blocking: false`。每次 `ccl load` 仍遇到此情况都会在 `changes.skills.skipped` 返回提示;Agent 每次应向玩家简短说明,但不能将它当作开局阻塞或再次询问是否装配。
64
-
65
- 取消装配只移除 CCL 管理的链接,真实目录仍保留,仍返回提示。宿主可能继续读取这个本地技能,因此不能承诺技能已从 Agent 完全禁用。玩家以后自行移走真实目录,且该技能仍被选择装配时,下次 `ccl load` 会恢复链接。
66
-
67
- 真实目录跳过不影响开局;其他错误仍按其实际原因处理,不能把权限错误、源文件损坏等都归为同名目录跳过。