@myclaw163/clawclaw-cli 0.8.14 → 0.8.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/docs/custom-modules/perception.md +4 -4
  2. package/docs/runtime/README.md +1 -1
  3. package/docs/runtime/behavior-runtime.md +1 -1
  4. package/docs/runtime/official-perception-modules.md +23 -30
  5. package/docs/runtime/perception-replay.md +1 -1
  6. package/package.json +1 -1
  7. package/scripts/sync-bundled-skill.mjs +28 -57
  8. package/skills/clawclaw/SKILL.md +6 -2
  9. package/skills/clawclaw/references/BEHAVIORS.md +16 -1
  10. package/skills/clawclaw/references/COMMANDS.md +1 -1
  11. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +310 -0
  12. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +684 -0
  13. package/skills/clawclaw/references/CUSTOM-MODULES.md +125 -0
  14. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +331 -0
  15. package/skills/clawclaw/references/HUB.md +2 -1
  16. package/src/commands/account.ts +36 -0
  17. package/src/commands/capability.ts +6 -1
  18. package/src/commands/load.ts +11 -0
  19. package/src/lib/agent-workspace-runtime.ts +2 -1
  20. package/src/lib/agent-workspace-skills.ts +235 -23
  21. package/src/lib/agent-workspace-sync.ts +17 -5
  22. package/src/lib/capability-cloud-refresh.ts +10 -1
  23. package/src/lib/capability-cloud-sync.ts +71 -1
  24. package/src/lib/capability-workspace.ts +2 -0
  25. package/src/lib/game-client.ts +10 -0
  26. package/src/runtime/clawclaw/behavior-decision.ts +4 -1
  27. package/src/runtime/clawclaw/owner.ts +79 -2
  28. package/src/runtime/clawclaw/plugins/assembly.ts +4 -0
  29. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +35 -2
  30. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +11 -7
  31. package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +3 -2
  32. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +46 -50
  33. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +39 -9
  34. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +167 -7
  35. package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-perception-report-adapter.ts +107 -0
  36. package/src/runtime/clawclaw/plugins/mailbox/index.ts +1 -0
  37. package/src/runtime/clawclaw/plugins/perception/module-runner.ts +86 -89
  38. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.ts +157 -41
  39. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +28 -4
  40. package/src/runtime/clawclaw/plugins/perception/perception-module-loader.ts +3 -1
  41. package/src/runtime/clawclaw/plugins/perception/perception-module-output.ts +30 -0
  42. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +126 -17
  43. package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-pool.ts +660 -0
  44. package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-worker.ts +262 -0
  45. package/src/runtime/clawclaw/plugins/trigger/trigger-module-loader.ts +41 -12
  46. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +252 -20
  47. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-pool.ts +496 -0
  48. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-worker.ts +164 -0
  49. package/src/runtime/clawclaw-event-catalog.ts +1 -0
  50. package/src/runtime/framework/events/memory-event-repository.ts +12 -0
  51. package/src/runtime/framework/modules/runtime-module-output.ts +24 -0
  52. package/src/runtime/framework/persistence/memory-first-persistence.ts +3 -0
  53. package/src/runtime/framework/plugins/contracts.ts +3 -0
  54. package/src/runtime/framework/plugins/runtime-input-journal.ts +12 -0
  55. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +150 -23
  56. package/src/runtime/framework/runtime.ts +18 -0
  57. package/src/runtime/framework/state/history/memory-state-history-repository.ts +10 -0
  58. package/src/runtime/game-sync-protocol.ts +47 -0
  59. package/src/runtime/observability/redaction.ts +28 -1
  60. package/src/runtime/ws-client.ts +7 -0
  61. package/src/sdk/perception-plugin/index.ts +13 -8
@@ -1,13 +1,23 @@
1
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
- import { dirname, join, resolve } from 'node:path';
1
+ import {
2
+ existsSync,
3
+ lstatSync,
4
+ mkdirSync,
5
+ readFileSync,
6
+ readdirSync,
7
+ renameSync,
8
+ writeFileSync,
9
+ } from 'node:fs';
10
+ import { dirname, join, relative, resolve } from 'node:path';
3
11
  import { randomUUID } from 'node:crypto';
4
12
  import type { AuthProfile } from './auth.js';
5
13
  import {
6
14
  resolveLocalAgentWorkspacePath,
15
+ type LocalAgentWorkspaceItem,
7
16
  type LocalAgentWorkspaceSnapshot,
8
17
  } from './agent-workspace-sync.js';
9
18
  import {
10
19
  capabilityWorkspacePath,
20
+ capabilityEntryForHubResource,
11
21
  readCapabilityWorkspaceRegistry,
12
22
  registerDiscoveredCapability,
13
23
  } from './capability-workspace.js';
@@ -21,17 +31,25 @@ import {
21
31
  linkAgentSkillTarget,
22
32
  overwriteAgentSkillTarget,
23
33
  readSkillName,
24
- resolveBundledClawclawSkill,
25
34
  unlinkAgentSkillTarget,
26
35
  type SkillHostMutationResult,
27
36
  } from './skill-host.js';
37
+ import { zipContentDigest } from './zip-store.js';
28
38
 
29
39
  interface ActiveSkillEntry {
30
40
  name: string;
31
- kind: 'official' | 'hub' | 'local';
41
+ kind: 'hub' | 'local';
32
42
  canonicalPath: string;
43
+ /** Last accepted remote directory hash. */
33
44
  sourceDigest?: string;
45
+ /** Latest observed remote directory hash. */
34
46
  remoteDigest?: string;
47
+ /** Upload-compatible digest for the last accepted remote content. */
48
+ sourceCloudDigest?: string;
49
+ /** Upload-compatible digest for the latest observed remote content. */
50
+ remoteCloudDigest?: string;
51
+ knownSourceDigests?: string[];
52
+ knownCloudDigests?: string[];
35
53
  resourceId?: string;
36
54
  versionId?: string;
37
55
  }
@@ -58,7 +76,12 @@ export interface AgentWorkspaceSkillDependencies {
58
76
  overwriteTarget?: (sourcePath: string, targetPath: string) => SkillHostMutationResult;
59
77
  linkTarget?: (sourcePath: string, targetPath: string) => SkillHostMutationResult;
60
78
  unlinkTarget?: (targetPath: string) => SkillHostMutationResult;
61
- bundledSkill?: () => string;
79
+ cloudDigest?: (path: string) => string | undefined;
80
+ }
81
+
82
+ export interface AccountSkillLinkSwitchResult {
83
+ removed: string[];
84
+ linked: string[];
62
85
  }
63
86
 
64
87
  function manifestPath(
@@ -98,6 +121,112 @@ function resultError(result: SkillHostMutationResult): string {
98
121
  return result.error ?? result.stderr?.trim() ?? 'skill host mutation failed';
99
122
  }
100
123
 
124
+ function skillCloudDigest(path: string): string | undefined {
125
+ if (!existsSync(path)) return undefined;
126
+ const root = resolve(path);
127
+ const files: Array<{ path: string; content: Buffer }> = [];
128
+ const visit = (directory: string): void => {
129
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
130
+ const child = join(directory, entry.name);
131
+ const stat = lstatSync(child);
132
+ if (stat.isSymbolicLink()) throw new Error('skill_source_symlink_unsupported');
133
+ if (stat.isDirectory()) visit(child);
134
+ else if (stat.isFile()) files.push({
135
+ path: relative(root, child).replaceAll('\\', '/'),
136
+ content: readFileSync(child),
137
+ });
138
+ }
139
+ };
140
+ try {
141
+ visit(root);
142
+ return files.length > 0 ? zipContentDigest(files) : undefined;
143
+ } catch {
144
+ return undefined;
145
+ }
146
+ }
147
+
148
+ function unique(values: Array<string | undefined>): string[] {
149
+ return [...new Set(values.filter((value): value is string => !!value))];
150
+ }
151
+
152
+ function accountManagedSkillSources(
153
+ workspaceDir: string,
154
+ profile: Pick<AuthProfile, 'apiKey'>,
155
+ ): Map<string, string> {
156
+ const skillsRoot = getUserDataAccountSkillsDir(workspaceDir, profile);
157
+ const sources = new Map<string, string>();
158
+ for (const [name] of Object.entries(readManifest(workspaceDir, profile).entries)) {
159
+ if (name === 'clawclaw') continue;
160
+ sources.set(name, join(skillsRoot, name));
161
+ }
162
+ for (const entry of Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)) {
163
+ if (
164
+ entry.type !== 'skill'
165
+ || entry.runtimeId === 'clawclaw'
166
+ || entry.origin !== 'local'
167
+ || entry.selection !== 'equipped'
168
+ ) continue;
169
+ sources.set(entry.runtimeId, capabilityWorkspacePath(workspaceDir, profile, entry));
170
+ }
171
+ return sources;
172
+ }
173
+
174
+ /**
175
+ * Move the device-wide account-managed Skill links before AuthStore commits an
176
+ * account switch. The package-owned clawclaw Skill is deliberately untouched.
177
+ */
178
+ export function switchActiveAccountSkillLinks(
179
+ workspaceDir: string,
180
+ previousProfile: Pick<AuthProfile, 'apiKey'> | null,
181
+ nextProfile: Pick<AuthProfile, 'apiKey'>,
182
+ dependencies: Pick<AgentWorkspaceSkillDependencies, 'targets' | 'linkTarget' | 'unlinkTarget'> = {},
183
+ ): AccountSkillLinkSwitchResult {
184
+ if (previousProfile?.apiKey === nextProfile.apiKey) return { removed: [], linked: [] };
185
+ const targets = dependencies.targets ?? agentSkillTargets;
186
+ const linkTarget = dependencies.linkTarget ?? linkAgentSkillTarget;
187
+ const unlinkTarget = dependencies.unlinkTarget ?? unlinkAgentSkillTarget;
188
+ const previous = previousProfile
189
+ ? accountManagedSkillSources(workspaceDir, previousProfile)
190
+ : new Map<string, string>();
191
+ const next = accountManagedSkillSources(workspaceDir, nextProfile);
192
+
193
+ for (const [name, source] of next) {
194
+ if (!existsSync(source) || readSkillName(source) !== name) {
195
+ throw new Error(`account_skill_source_unavailable:${name}`);
196
+ }
197
+ }
198
+
199
+ const removedTargets: Array<{ name: string; target: string }> = [];
200
+ const linkedTargets: Array<{ name: string; target: string }> = [];
201
+ try {
202
+ for (const [name] of previous) {
203
+ for (const target of targets(name)) {
204
+ const result = unlinkTarget(target);
205
+ if (!result.ok) throw new Error(`account_skill_unlink_failed:${name}:${resultError(result)}`);
206
+ removedTargets.push({ name, target });
207
+ }
208
+ }
209
+ for (const [name, source] of next) {
210
+ for (const target of targets(name)) {
211
+ const result = linkTarget(source, target);
212
+ if (!result.ok) throw new Error(`account_skill_link_failed:${name}:${resultError(result)}`);
213
+ linkedTargets.push({ name, target });
214
+ }
215
+ }
216
+ } catch (error) {
217
+ for (const { target } of linkedTargets.reverse()) unlinkTarget(target);
218
+ for (const { name, target } of removedTargets.reverse()) {
219
+ const source = previous.get(name);
220
+ if (source && existsSync(source)) linkTarget(source, target);
221
+ }
222
+ throw error;
223
+ }
224
+ return {
225
+ removed: [...previous.keys()],
226
+ linked: [...next.keys()],
227
+ };
228
+ }
229
+
101
230
  export function syncAgentWorkspaceSkills(
102
231
  workspaceDir: string,
103
232
  profile: Pick<AuthProfile, 'apiKey'>,
@@ -112,6 +241,7 @@ export function syncAgentWorkspaceSkills(
112
241
  const linkTarget = dependencies.linkTarget ?? linkAgentSkillTarget;
113
242
  const unlinkTarget = dependencies.unlinkTarget ?? unlinkAgentSkillTarget;
114
243
  const targets = dependencies.targets ?? agentSkillTargets;
244
+ const cloudDigest = dependencies.cloudDigest ?? skillCloudDigest;
115
245
  const skillsRoot = getUserDataAccountSkillsDir(workspaceDir, profile);
116
246
  mkdirSync(skillsRoot, { recursive: true });
117
247
 
@@ -121,10 +251,10 @@ export function syncAgentWorkspaceSkills(
121
251
  resourceId?: string;
122
252
  versionId?: string;
123
253
  remoteDigest?: string;
254
+ remoteCloudDigest?: string;
124
255
  publisher?: 'official' | 'self' | 'community';
256
+ remoteItem?: LocalAgentWorkspaceItem;
125
257
  }>();
126
- const bundled = (dependencies.bundledSkill ?? resolveBundledClawclawSkill)();
127
- desired.set('clawclaw', { kind: 'official', sourcePath: bundled });
128
258
 
129
259
  for (const item of snapshot.items.skill) {
130
260
  if (!item.skillRootPath) continue;
@@ -150,12 +280,22 @@ export function syncAgentWorkspaceSkills(
150
280
  resourceId: item.resourceId,
151
281
  versionId: item.versionId,
152
282
  remoteDigest: hashDirectory(path),
283
+ remoteCloudDigest: cloudDigest(path),
153
284
  publisher: item.hub?.publisher ?? 'community',
285
+ remoteItem: item,
154
286
  });
155
287
  }
156
288
 
157
289
  for (const entry of Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)) {
158
290
  if (entry.type !== 'skill' || entry.origin !== 'local' || entry.selection !== 'equipped') continue;
291
+ if (entry.runtimeId === 'clawclaw') {
292
+ failed.push({
293
+ name: entry.runtimeId,
294
+ action: 'add',
295
+ error: 'The official clawclaw Skill is managed by the installed CCL package',
296
+ });
297
+ continue;
298
+ }
159
299
  const path = capabilityWorkspacePath(workspaceDir, profile, entry);
160
300
  if (desired.has(entry.runtimeId)) {
161
301
  failed.push({ name: entry.runtimeId, action: 'add', error: 'local and Hub Skill names conflict' });
@@ -174,33 +314,69 @@ export function syncAgentWorkspaceSkills(
174
314
  const canonical = join(skillsRoot, name);
175
315
  const previous = current.entries[name];
176
316
  const sourceDigest = hashDirectory(item.sourcePath);
177
- if (!sourceDigest) {
317
+ const sourceCloudDigest = item.remoteCloudDigest ?? cloudDigest(item.sourcePath);
318
+ if (!sourceDigest || !sourceCloudDigest) {
178
319
  failed.push({ name, action: previous ? 'update' : 'add', error: 'Skill source is unreadable' });
179
320
  continue;
180
321
  }
181
322
  const canonicalDigest = hashDirectory(canonical);
323
+ const canonicalCloudDigest = cloudDigest(canonical);
324
+ const registered = item.kind === 'hub' && item.resourceId
325
+ ? capabilityEntryForHubResource(workspaceDir, profile, 'skill', item.resourceId)
326
+ : undefined;
327
+ const knownSourceDigests = unique([
328
+ ...(previous?.knownSourceDigests ?? []),
329
+ previous?.sourceDigest,
330
+ previous?.remoteDigest,
331
+ sourceDigest,
332
+ ]);
333
+ const knownCloudDigests = unique([
334
+ ...(previous?.knownCloudDigests ?? []),
335
+ previous?.sourceCloudDigest,
336
+ previous?.remoteCloudDigest,
337
+ registered?.hub?.baseSha256,
338
+ registered?.hub?.lastUploadedSha256,
339
+ sourceCloudDigest,
340
+ ]);
182
341
  let applied = false;
183
342
  let preserved = false;
343
+ let resolution: LocalAgentWorkspaceItem['resolution'] = 'hub';
184
344
  if (item.kind === 'local' && resolve(item.sourcePath) === resolve(canonical)) {
185
345
  applied = true;
186
- } else if (item.kind === 'official') {
187
- if (canonicalDigest !== sourceDigest) {
188
- const result = overwriteTarget(item.sourcePath, canonical);
189
- if (!result.ok) {
190
- failed.push({ name, action: previous ? 'update' : 'add', error: resultError(result) });
191
- continue;
192
- }
193
- applied = true;
194
- }
195
346
  } else if (canonicalDigest === sourceDigest) {
196
347
  applied = true;
197
- } else if (canonicalDigest === undefined || canonicalDigest === previous?.sourceDigest) {
348
+ } else if (canonicalDigest === undefined) {
198
349
  const result = overwriteTarget(item.sourcePath, canonical);
199
350
  if (!result.ok) {
200
351
  failed.push({ name, action: previous ? 'update' : 'add', error: resultError(result) });
201
352
  continue;
202
353
  }
203
354
  applied = true;
355
+ } else if (item.kind === 'hub') {
356
+ const originRecognized = registered?.hub?.localOriginUnrecognized !== true
357
+ && (!!registered?.hub || !!previous?.sourceDigest);
358
+ const localMatchesKnownVersion = knownSourceDigests.includes(canonicalDigest)
359
+ || (!!canonicalCloudDigest && knownCloudDigests.includes(canonicalCloudDigest));
360
+ const remoteAdvanced = registered?.hub
361
+ ? registered.hub.versionId !== item.versionId
362
+ : !!previous?.sourceDigest && previous.sourceDigest !== sourceDigest;
363
+ if (localMatchesKnownVersion) {
364
+ const result = overwriteTarget(item.sourcePath, canonical);
365
+ if (!result.ok) {
366
+ failed.push({ name, action: previous ? 'update' : 'add', error: resultError(result) });
367
+ continue;
368
+ }
369
+ applied = true;
370
+ resolution = 'known_online_old';
371
+ } else {
372
+ preserved = true;
373
+ resolution = !originRecognized
374
+ ? 'local_origin_unrecognized'
375
+ : remoteAdvanced
376
+ ? 'concurrent_difference'
377
+ : 'local_modified';
378
+ preservedModified.push(name);
379
+ }
204
380
  } else {
205
381
  preserved = true;
206
382
  preservedModified.push(name);
@@ -220,6 +396,28 @@ export function syncAgentWorkspaceSkills(
220
396
  }
221
397
  }
222
398
  if (linkFailed) continue;
399
+ const effectiveCloudDigest = cloudDigest(canonical);
400
+ if (!effectiveCloudDigest) {
401
+ failed.push({ name, action: previous ? 'update' : 'add', error: 'Canonical Skill is unreadable' });
402
+ continue;
403
+ }
404
+ if (item.remoteItem) {
405
+ item.remoteItem.resolution = resolution;
406
+ if (resolution === 'hub' || resolution === 'known_online_old') {
407
+ delete item.remoteItem.localContentDigest;
408
+ delete item.remoteItem.localModifiedAtMs;
409
+ } else {
410
+ item.remoteItem.localContentDigest = effectiveCloudDigest;
411
+ }
412
+ }
413
+ const acceptedVersionId = preserved
414
+ ? registered?.hub?.versionId ?? item.versionId
415
+ : item.versionId;
416
+ const acceptedCloudDigest = preserved
417
+ ? registered?.hub?.baseSha256
418
+ ?? previous?.sourceCloudDigest
419
+ ?? (registered?.hub?.versionId === item.versionId ? sourceCloudDigest : undefined)
420
+ : sourceCloudDigest;
223
421
  registerDiscoveredCapability(workspaceDir, profile, {
224
422
  type: 'skill',
225
423
  path: canonical,
@@ -230,9 +428,16 @@ export function syncAgentWorkspaceSkills(
230
428
  ...(item.kind === 'hub' && item.resourceId && item.versionId ? {
231
429
  hub: {
232
430
  resourceId: item.resourceId,
233
- versionId: item.versionId,
431
+ versionId: acceptedVersionId!,
432
+ workspaceItemId: item.remoteItem?.workspaceItemId,
234
433
  publisher: item.publisher ?? 'community',
235
- baseSha256: item.remoteDigest,
434
+ baseSha256: acceptedCloudDigest,
435
+ observedCloudVersionId: resolution === 'concurrent_difference'
436
+ ? item.versionId
437
+ : undefined,
438
+ localOriginUnrecognized: resolution === 'local_origin_unrecognized'
439
+ ? true
440
+ : undefined,
236
441
  },
237
442
  } : {}),
238
443
  });
@@ -240,8 +445,15 @@ export function syncAgentWorkspaceSkills(
240
445
  name,
241
446
  kind: item.kind,
242
447
  canonicalPath: canonical,
243
- sourceDigest: preserved ? previous?.sourceDigest : sourceDigest,
244
- remoteDigest: item.remoteDigest,
448
+ sourceDigest: preserved
449
+ ? previous?.sourceDigest
450
+ ?? (registered?.hub?.versionId === item.versionId ? sourceDigest : undefined)
451
+ : sourceDigest,
452
+ remoteDigest: sourceDigest,
453
+ sourceCloudDigest: acceptedCloudDigest,
454
+ remoteCloudDigest: sourceCloudDigest,
455
+ knownSourceDigests,
456
+ knownCloudDigests,
245
457
  resourceId: item.resourceId,
246
458
  versionId: item.versionId,
247
459
  };
@@ -251,7 +463,7 @@ export function syncAgentWorkspaceSkills(
251
463
  }
252
464
 
253
465
  for (const [name] of Object.entries(current.entries)) {
254
- if (desired.has(name)) continue;
466
+ if (name === 'clawclaw' || desired.has(name)) continue;
255
467
  let failedRemoval = false;
256
468
  for (const target of targets(name)) {
257
469
  const result = unlinkTarget(target);
@@ -72,7 +72,12 @@ export interface LocalAgentWorkspaceItem {
72
72
  contentDigest: string;
73
73
  sourceSha256: string;
74
74
  }>;
75
- resolution?: 'hub' | 'local_modified' | 'concurrent_difference' | 'known_online_old';
75
+ resolution?:
76
+ | 'hub'
77
+ | 'local_modified'
78
+ | 'concurrent_difference'
79
+ | 'known_online_old'
80
+ | 'local_origin_unrecognized';
76
81
  localContentDigest?: string;
77
82
  localModifiedAtMs?: number;
78
83
  }
@@ -398,6 +403,7 @@ interface LocalOverride {
398
403
  sha256: string;
399
404
  contentDigest: string;
400
405
  modifiedAtMs: number;
406
+ originRecognized: boolean;
401
407
  }
402
408
 
403
409
  interface WorkingCopyMetadata {
@@ -600,7 +606,9 @@ function inspectLocalSnapshot(
600
606
  }
601
607
  const localDigest = singleFileContentDigest(source.relativePath, bytes);
602
608
  const modifiedAtMs = statSync(workingPath).mtimeMs;
603
- item.resolution = 'local_modified';
609
+ item.resolution = item.resolution === 'local_origin_unrecognized'
610
+ ? 'local_origin_unrecognized'
611
+ : 'local_modified';
604
612
  item.localContentDigest = localDigest;
605
613
  item.localModifiedAtMs = modifiedAtMs;
606
614
  if (projectionSha !== localSha) projectionOutdated = true;
@@ -609,6 +617,7 @@ function inspectLocalSnapshot(
609
617
  sha256: localSha,
610
618
  contentDigest: localDigest,
611
619
  modifiedAtMs,
620
+ originRecognized: item.resolution !== 'local_origin_unrecognized',
612
621
  });
613
622
  }
614
623
  }
@@ -753,6 +762,7 @@ export async function syncAgentWorkspaceConfig(
753
762
  bytes,
754
763
  ),
755
764
  modifiedAtMs: statSync(workingPath).mtimeMs,
765
+ originRecognized: persistedWorkingMetadata !== undefined,
756
766
  };
757
767
  }
758
768
  }
@@ -774,9 +784,11 @@ export async function syncAgentWorkspaceConfig(
774
784
  && !persistedWorkingMetadata.knownVersions.some(
775
785
  (entry) => entry.versionId === materialized.versionId,
776
786
  );
777
- materialized.resolution = remoteAdvancedFromLocalBaseline
778
- ? 'concurrent_difference'
779
- : 'local_modified';
787
+ materialized.resolution = !override.originRecognized
788
+ ? 'local_origin_unrecognized'
789
+ : remoteAdvancedFromLocalBaseline
790
+ ? 'concurrent_difference'
791
+ : 'local_modified';
780
792
  materialized.localContentDigest = override.contentDigest;
781
793
  materialized.localModifiedAtMs = override.modifiedAtMs;
782
794
  } else {
@@ -242,9 +242,17 @@ export async function refreshCapabilitiesFromCloud(
242
242
  }
243
243
  const detail = await client.getResource(type, hub.resourceId, workspaceItemId);
244
244
  if (detail.versionId === hub.versionId) {
245
- if (hub.observedCloudVersionId) updateCapabilityHubIdentity(workspaceDir, profile, entry.key, {
245
+ if (
246
+ hub.observedCloudVersionId
247
+ || (hub.localOriginUnrecognized && (
248
+ before === hub.baseSha256 || before === hub.lastUploadedSha256
249
+ ))
250
+ ) updateCapabilityHubIdentity(workspaceDir, profile, entry.key, {
246
251
  ...hub,
247
252
  observedCloudVersionId: undefined,
253
+ localOriginUnrecognized: before === hub.baseSha256 || before === hub.lastUploadedSha256
254
+ ? undefined
255
+ : hub.localOriginUnrecognized,
248
256
  });
249
257
  result.unchanged.push({ type: entry.type, id: entry.runtimeId });
250
258
  continue;
@@ -289,6 +297,7 @@ export async function refreshCapabilitiesFromCloud(
289
297
  baseSha256: artifact.digest,
290
298
  lastUploadedSha256: artifact.digest,
291
299
  observedCloudVersionId: undefined,
300
+ localOriginUnrecognized: undefined,
292
301
  });
293
302
  result.downloaded.push({
294
303
  type: entry.type,
@@ -1,9 +1,11 @@
1
1
  import {
2
+ existsSync,
2
3
  lstatSync,
3
4
  readFileSync,
5
+ realpathSync,
4
6
  readdirSync,
5
7
  } from 'node:fs';
6
- import { basename, extname, join, relative } from 'node:path';
8
+ import { basename, dirname, extname, join, relative } from 'node:path';
7
9
  import { createHash } from 'node:crypto';
8
10
  import type { AuthProfile } from './auth.js';
9
11
  import {
@@ -21,7 +23,14 @@ import {
21
23
  type ResourceType,
22
24
  } from './hub-client.js';
23
25
  import type { LocalAgentWorkspaceSnapshot } from './agent-workspace-sync.js';
26
+ import { readSkillName } from './skill-host.js';
24
27
  import { createStoredZip, zipContentDigest, type ZipStoreEntry } from './zip-store.js';
28
+ import {
29
+ inspectClawclawBehaviorSource,
30
+ } from '../runtime/clawclaw/plugins/behavior/behavior-source.js';
31
+ import {
32
+ listClawclawPerceptionSourcesInDirectory,
33
+ } from '../runtime/clawclaw/plugins/perception/perception-source.js';
25
34
 
26
35
  export interface CapabilityCloudSyncChange {
27
36
  type: CapabilityWorkspaceType;
@@ -46,10 +55,17 @@ export interface CapabilityCloudSyncFailure {
46
55
  error: string;
47
56
  }
48
57
 
58
+ export interface CapabilityCloudSyncSkip {
59
+ type: CapabilityWorkspaceType;
60
+ id: string;
61
+ reason: 'local_origin_unrecognized';
62
+ }
63
+
49
64
  export interface CapabilityCloudSyncResult {
50
65
  uploaded: CapabilityCloudSyncChange[];
51
66
  conflicts: CapabilityCloudSyncConflict[];
52
67
  failed: CapabilityCloudSyncFailure[];
68
+ skipped: CapabilityCloudSyncSkip[];
53
69
  unchanged: Array<{ type: CapabilityWorkspaceType; id: string }>;
54
70
  }
55
71
 
@@ -138,6 +154,44 @@ function snapshotResolution(
138
154
  .find((item) => item.resourceId === resourceId)?.resolution;
139
155
  }
140
156
 
157
+ const MAX_CAPABILITY_UPLOAD_BYTES = 10 * 1024 * 1024;
158
+
159
+ function validateUploadPayload(
160
+ entry: CapabilityWorkspaceEntry,
161
+ path: string,
162
+ payload: ReturnType<typeof uploadPayload>,
163
+ ): void {
164
+ const totalBytes = payload.source.reduce((total, file) => total + file.bytes.length, 0);
165
+ if (totalBytes > MAX_CAPABILITY_UPLOAD_BYTES) {
166
+ throw new Error('capability_validation_failed:content_too_large');
167
+ }
168
+ if (entry.type === 'behavior') {
169
+ const source = inspectClawclawBehaviorSource(path, dirname(path));
170
+ if (!source || source.id !== entry.runtimeId) {
171
+ throw new Error('capability_validation_failed:behavior_invalid');
172
+ }
173
+ return;
174
+ }
175
+ if (entry.type === 'perception') {
176
+ const resolvedPath = realpathSync(path);
177
+ const source = listClawclawPerceptionSourcesInDirectory(dirname(path))
178
+ .find((candidate) => realpathSync(candidate.sourcePath) === resolvedPath);
179
+ if (!source || source.id !== entry.runtimeId) {
180
+ throw new Error('capability_validation_failed:perception_invalid');
181
+ }
182
+ return;
183
+ }
184
+ if (entry.type === 'persona') {
185
+ if (!existsSync(path) || extname(path).toLowerCase() !== '.md') {
186
+ throw new Error('capability_validation_failed:persona_invalid');
187
+ }
188
+ return;
189
+ }
190
+ if (readSkillName(path) !== entry.runtimeId) {
191
+ throw new Error('capability_validation_failed:skill_invalid');
192
+ }
193
+ }
194
+
141
195
  export async function syncCapabilitiesToCloud(
142
196
  workspaceDir: string,
143
197
  profile: Pick<AuthProfile, 'apiKey' | 'serverUrl'>,
@@ -149,6 +203,7 @@ export async function syncCapabilitiesToCloud(
149
203
  uploaded: [],
150
204
  conflicts: [],
151
205
  failed: [],
206
+ skipped: [],
152
207
  unchanged: [],
153
208
  };
154
209
  const selectedKeys = dependencies.entryKeys ? new Set(dependencies.entryKeys) : undefined;
@@ -188,6 +243,20 @@ export async function syncCapabilitiesToCloud(
188
243
  });
189
244
  continue;
190
245
  }
246
+ if (
247
+ (
248
+ entry.hub?.localOriginUnrecognized
249
+ || (entry.hub && snapshotResolution(snapshot, entry.hub.resourceId) === 'local_origin_unrecognized')
250
+ )
251
+ && entry.conflictChoice !== 'local'
252
+ ) {
253
+ result.skipped.push({
254
+ type: entry.type,
255
+ id: entry.runtimeId,
256
+ reason: 'local_origin_unrecognized',
257
+ });
258
+ continue;
259
+ }
191
260
  if (
192
261
  entry.hub?.observedCloudVersionId
193
262
  && entry.hub.observedCloudVersionId !== entry.hub.versionId
@@ -234,6 +303,7 @@ export async function syncCapabilitiesToCloud(
234
303
  }
235
304
  baseVersionId = latest.versionId;
236
305
  }
306
+ validateUploadPayload(entry, path, payload);
237
307
  const uploadedSource = await client.uploadFiles(sourceFileType(entry.type), payload.source);
238
308
  let packageFileId: string | undefined;
239
309
  if (payload.packageUpload) {
@@ -29,6 +29,8 @@ export interface CapabilityHubIdentity {
29
29
  lastUploadedSha256?: string;
30
30
  pendingBackpackRestoreResourceId?: string;
31
31
  observedCloudVersionId?: string;
32
+ /** The working copy existed before CCL had a trustworthy Hub baseline. */
33
+ localOriginUnrecognized?: boolean;
32
34
  }
33
35
 
34
36
  export interface CapabilityWorkspaceEntry {
@@ -13,6 +13,7 @@ import {
13
13
  } from '../runtime/ws-client.js';
14
14
  import { RuntimeLogger } from '../runtime/runtime-logger.js';
15
15
  import type { RawWsMessageSink } from '../runtime/raw-ws-log.js';
16
+ import type { GameSyncPerceptionReport } from '../runtime/game-sync-protocol.js';
16
17
  import type { QueueMode } from './competition.js';
17
18
  import type {
18
19
  CreateRoomOptions,
@@ -514,6 +515,15 @@ export class GameClient {
514
515
  this.rememberGameSyncResumeState(this.ws?.resumeState);
515
516
  }
516
517
 
518
+ /** Send display-only perception output over the active GameSync connection. */
519
+ reportGameSyncPerceptions(perceptions: readonly GameSyncPerceptionReport[]): boolean {
520
+ return this.ws?.reportPerceptions(perceptions) ?? false;
521
+ }
522
+
523
+ get gameSyncLocale(): 'zh-CN' | 'en-US' {
524
+ return this.ws?.resumeState?.locale ?? this.gameSyncResumeState?.locale ?? 'zh-CN';
525
+ }
526
+
517
527
  /**
518
528
  * Try to discover game server from /queue/status.
519
529
  * If found and WS is enabled, reconnects WS to the game server.
@@ -2,6 +2,7 @@ import type {
2
2
  BehaviorDecision,
3
3
  FiniteBehaviorDecision,
4
4
  } from '../../sdk/behavior-plugin/index.js';
5
+ import { assertRuntimeModuleOutputSize } from '../framework/modules/runtime-module-output.js';
5
6
 
6
7
  const DECISION_KEYS = new Set(['actions', 'status', 'events', 'delegate', 'finish']);
7
8
  const STATUS_KEYS = new Set(['summary', 'activity', 'room', 'task', 'targetPlayer', 'data']);
@@ -85,5 +86,7 @@ export function normalizeBehaviorDecision(
85
86
  throw new Error('behavior_finish_summary_invalid');
86
87
  }
87
88
  }
88
- return Object.freeze(structuredClone(source)) as BehaviorDecision | FiniteBehaviorDecision;
89
+ const normalized = Object.freeze(structuredClone(source)) as BehaviorDecision | FiniteBehaviorDecision;
90
+ assertRuntimeModuleOutputSize(normalized, 'behavior_output');
91
+ return normalized;
89
92
  }