@myclaw163/clawclaw-cli 0.10.5 → 0.10.7

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 (57) hide show
  1. package/dist/strategy-worker/assets/clawclaw-spatial-facts.json +1383 -0
  2. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-3VLVCU6P.js +71 -0
  3. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-ATQQZA4X.js +44 -0
  4. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-CF6IEQ4V.js +12 -0
  5. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-QEPKDSLE.js +278 -0
  6. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-ZQILO6OM.js +0 -0
  7. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/clawclaw-walkable.bin +0 -0
  8. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/host.js +1388 -0
  9. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-behavior-plugin.js +22 -0
  10. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-module-input.js +0 -0
  11. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-perception-plugin.js +72 -0
  12. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-sdk.js +3034 -0
  13. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-strategy-plugin.js +25 -0
  14. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-trigger-plugin.js +16 -0
  15. package/docs/custom-modules/api-reference.md +10 -8
  16. package/docs/custom-modules/perception.md +26 -3
  17. package/docs/runtime/behavior-runtime.md +3 -1
  18. package/docs/runtime/official-perception-modules.md +2 -2
  19. package/docs/user-guide/behavior.md +3 -1
  20. package/package.json +5 -3
  21. package/scripts/build-strategy-worker.mjs +28 -0
  22. package/scripts/migrate-official-perceptions.mjs +157 -0
  23. package/skills/clawclaw/SKILL.md +17 -6
  24. package/skills/clawclaw/references/BEHAVIORS.md +2 -0
  25. package/skills/clawclaw/references/COMMANDS.md +3 -3
  26. package/skills/clawclaw/references/GAME-MECHANICS.md +12 -10
  27. package/skills/clawclaw/references/TACTICS.md +417 -29
  28. package/skills/clawclaw-creator/SKILL.md +3 -1
  29. package/skills/clawclaw-creator/references/CUSTOM-MODULE-API.md +10 -8
  30. package/skills/clawclaw-creator/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +26 -3
  31. package/skills/clawclaw-creator/references/CUSTOM-SKILL-DEVELOPMENT.md +1 -1
  32. package/src/commands/capability.ts +4 -2
  33. package/src/commands/load.ts +5 -2
  34. package/src/lib/agent-workspace-skills.ts +12 -7
  35. package/src/lib/capability-cloud-sync.ts +13 -7
  36. package/src/lib/capability-discovery.ts +10 -3
  37. package/src/lib/capability-selection.ts +7 -0
  38. package/src/lib/package-skills.ts +11 -1
  39. package/src/runtime/clawclaw/behavior-start-control.ts +114 -0
  40. package/src/runtime/clawclaw/owner.ts +19 -4
  41. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +1 -0
  42. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +11 -6
  43. package/src/runtime/clawclaw/plugins/behavior/behavior-module-loader.ts +48 -1
  44. package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +2 -0
  45. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +28 -6
  46. package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +25 -3
  47. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +1 -1
  48. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +9 -0
  49. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +3 -0
  50. package/src/runtime/clawclaw/plugins/perception/module-input-boundary.ts +64 -0
  51. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +37 -49
  52. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +3 -1
  53. package/src/runtime/clawclaw/plugins/system-perception/sabotage-availability-rule.ts +2 -0
  54. package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +122 -61
  55. package/src/sdk/perception-plugin/index.ts +1 -0
  56. package/src/sdk/perception-plugin/lifecycle.ts +15 -0
  57. package/src/sdk/perception-plugin/module.ts +15 -0
@@ -1,5 +1,5 @@
1
1
  import { accountRequiredMessage } from '../lib/desktop-mode.js';
2
- import { isPackageManagedSkill } from '../lib/package-skills.js';
2
+ import { isPackageManagedSkill, PACKAGE_MANAGED_SKILL_NAMES } from '../lib/package-skills.js';
3
3
  import { Command, InvalidArgumentError } from 'commander';
4
4
  import { AuthStore, type AuthProfile } from '../lib/auth.js';
5
5
  import { discoverLocalCapabilities } from '../lib/capability-discovery.js';
@@ -240,10 +240,12 @@ export function createCapabilityCommand(dependencies: CapabilityCommandDependenc
240
240
  .action(() => {
241
241
  const workspaceDir = getWorkspaceDir();
242
242
  const profile = activeProfile();
243
- discoverLocalCapabilities(workspaceDir, profile);
243
+ const { reservedSkills } = discoverLocalCapabilities(workspaceDir, profile);
244
244
  console.log(JSON.stringify({
245
245
  capabilities: Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
246
246
  .map(entry => ({ ...entry, selection_ref: capabilitySelectionRef(entry) })),
247
+ reserved_skill_names: PACKAGE_MANAGED_SKILL_NAMES,
248
+ ...(reservedSkills.length ? { skipped_skills: reservedSkills } : {}),
247
249
  }, null, 2));
248
250
  }));
249
251
 
@@ -919,10 +919,12 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
919
919
  } : undefined;
920
920
  const selectionRequired = pendingCapabilitySelections(workspaceDir, profile);
921
921
  const blockedSkillNames = skillConflictNames(skillChanges.conflicts ?? []);
922
+ const reservedSkillPaths = new Set(discoveredLocal.reservedSkills.map(skill => skill.path));
922
923
  const skills = [...new Set(Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
923
924
  .filter((entry) => entry.type === 'skill' && entry.selection === 'equipped'
924
925
  && !blockedSkillNames.has(skillNameKey(entry.runtimeId))
925
- && !entry.hub?.cloudStatus && !isPackageManagedSkill(entry.runtimeId))
926
+ && !entry.hub?.cloudStatus && !isPackageManagedSkill(entry.runtimeId)
927
+ && !reservedSkillPaths.has(capabilityWorkspacePath(workspaceDir, profile, entry)))
926
928
  .map((entry) => entry.runtimeId).concat((skillChanges.conflicts ?? [])
927
929
  .flatMap(item => item.active ? [item.active.id ?? item.active.name] : [])))].sort();
928
930
  console.log(JSON.stringify({
@@ -936,8 +938,9 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
936
938
  revision: activeWorkspace?.revision ?? null,
937
939
  ...(workspaceSyncError ? { error: workspaceSyncError } : {}),
938
940
  },
939
- ...(skillChangeSummary || cloudChangeSummary ? {
941
+ ...(skillChangeSummary || cloudChangeSummary || discoveredLocal.reservedSkills.length ? {
940
942
  changes: {
943
+ ...(discoveredLocal.reservedSkills.length ? { skipped_local_skills: discoveredLocal.reservedSkills } : {}),
941
944
  ...(skillChangeSummary ? { skills: skillChangeSummary } : {}),
942
945
  ...(cloudChangeSummary ? { cloud_sync: cloudChangeSummary } : {}),
943
946
  },
@@ -1,4 +1,4 @@
1
- import { isPackageManagedSkill } from './package-skills.js';
1
+ import { isPackageManagedSkill, reservedSkillName } from './package-skills.js';
2
2
  import {
3
3
  existsSync,
4
4
  lstatSync,
@@ -232,8 +232,10 @@ function accountManagedSkillSources(
232
232
  ? entry.hub?.resourceId === manifestEntry.resourceId
233
233
  : capabilityWorkspacePath(workspaceDir, profile, entry) === manifestEntry.canonicalPath));
234
234
  if (conflictingNames.has(skillNameKey(name)) && entry?.selection !== 'equipped') continue;
235
- if (!includeInactive && entry && (entry.selection !== 'equipped' || entry.hub?.cloudStatus)) continue;
236
- sources.set(name, manifestEntry.canonicalPath ?? join(skillsRoot, name));
235
+ const path = manifestEntry.canonicalPath ?? join(skillsRoot, name);
236
+ if (!includeInactive && (reservedSkillName(readSkillName(path), path)
237
+ || (entry && (entry.selection !== 'equipped' || entry.hub?.cloudStatus)))) continue;
238
+ sources.set(name, path);
237
239
  }
238
240
  for (const entry of Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)) {
239
241
  if (
@@ -243,7 +245,9 @@ function accountManagedSkillSources(
243
245
  || entry.selection !== 'equipped'
244
246
  || conflictingNames.has(skillNameKey(entry.runtimeId))
245
247
  ) continue;
246
- sources.set(entry.runtimeId, capabilityWorkspacePath(workspaceDir, profile, entry));
248
+ const path = capabilityWorkspacePath(workspaceDir, profile, entry);
249
+ if (!includeInactive && reservedSkillName(readSkillName(path), path)) continue;
250
+ sources.set(entry.runtimeId, path);
247
251
  }
248
252
  return sources;
249
253
  }
@@ -383,11 +387,12 @@ export function syncAgentWorkspaceSkills(
383
387
  const path = capabilityWorkspacePath(workspaceDir, profile, entry);
384
388
  const name = readSkillName(path) ?? entry.runtimeId;
385
389
  if (blockedNames.has(skillNameKey(name))) continue;
386
- if (isPackageManagedSkill(entry.runtimeId)) {
390
+ const reserved = reservedSkillName(entry.runtimeId) ?? reservedSkillName(name, path);
391
+ if (reserved) {
387
392
  failed.push({
388
- name: entry.runtimeId,
393
+ name: reserved,
389
394
  action: 'add',
390
- error: `The official ${entry.runtimeId} Skill is managed by the installed CCL package`,
395
+ error: `The official ${reserved} Skill is managed by the installed CCL package`,
391
396
  });
392
397
  continue;
393
398
  }
@@ -1,4 +1,4 @@
1
- import { isPackageManagedSkill } from './package-skills.js';
1
+ import { reservedSkillName } from './package-skills.js';
2
2
  import {
3
3
  existsSync,
4
4
  lstatSync,
@@ -64,7 +64,7 @@ export interface CapabilityCloudSyncFailure extends Partial<HubErrorFields> {
64
64
  export interface CapabilityCloudSyncSkip {
65
65
  type: CapabilityWorkspaceType;
66
66
  id: string;
67
- reason: 'local_origin_unrecognized' | 'fork_relationship_unresolved' | 'skill_name_conflict';
67
+ reason: 'local_origin_unrecognized' | 'fork_relationship_unresolved' | 'skill_name_conflict' | 'reserved_skill_name';
68
68
  }
69
69
 
70
70
  export interface CapabilityCloudSyncResult {
@@ -251,14 +251,20 @@ export async function syncCapabilitiesToCloud(
251
251
  ? [item.resourceId, item.forkReconciliation.parentResourceId] : []));
252
252
  const entries = Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries)
253
253
  .filter((entry) => (
254
- (entry.type !== 'skill' || !isPackageManagedSkill(entry.runtimeId))
255
- && !entry.hub?.cloudStatus
254
+ !entry.hub?.cloudStatus
256
255
  && (!selectedKeys || selectedKeys.has(entry.key))
257
256
  ));
258
257
  for (const entry of entries) {
259
- if (entry.type === 'skill' && blockedSkillNames.has(skillNameKey(skillNameCandidate(workspaceDir, profile, entry).name))) {
260
- result.skipped.push({ type: entry.type, id: entry.runtimeId, reason: 'skill_name_conflict' });
261
- continue;
258
+ if (entry.type === 'skill') {
259
+ const skill = skillNameCandidate(workspaceDir, profile, entry);
260
+ if (reservedSkillName(entry.runtimeId) || reservedSkillName(skill.name, skill.working_copy_path)) {
261
+ result.skipped.push({ type: entry.type, id: entry.runtimeId, reason: 'reserved_skill_name' });
262
+ continue;
263
+ }
264
+ if (blockedSkillNames.has(skillNameKey(skill.name))) {
265
+ result.skipped.push({ type: entry.type, id: entry.runtimeId, reason: 'skill_name_conflict' });
266
+ continue;
267
+ }
262
268
  }
263
269
  if (entry.hub && (entry.hub.forkRelationshipUnresolved || unresolvedForks.has(entry.hub.resourceId))) {
264
270
  result.skipped.push({ type: entry.type, id: entry.runtimeId, reason: 'fork_relationship_unresolved' });
@@ -1,4 +1,4 @@
1
- import { isPackageManagedSkill } from './package-skills.js';
1
+ import { reservedSkillName } from './package-skills.js';
2
2
  import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import type { AuthProfile } from './auth.js';
@@ -31,6 +31,7 @@ export interface DiscoveredLocalCapabilities {
31
31
  perceptions: Array<{ source: ResolvedClawclawPerceptionSource; entry: CapabilityWorkspaceEntry }>;
32
32
  personas: CapabilityWorkspaceEntry[];
33
33
  skills: CapabilityWorkspaceEntry[];
34
+ reservedSkills: Array<{ name: string; path: string; reason: 'reserved_skill_name' }>;
34
35
  }
35
36
 
36
37
  export function discoverLocalCapabilities(
@@ -73,6 +74,7 @@ export function discoverLocalCapabilities(
73
74
  description: `Persona ${preset.name}`,
74
75
  }));
75
76
  const skillsRoot = getUserDataAccountSkillsDir(workspaceDir, profile);
77
+ const reservedSkills: DiscoveredLocalCapabilities['reservedSkills'] = [];
76
78
  const skills = existsSync(skillsRoot)
77
79
  ? readdirSync(skillsRoot, { withFileTypes: true }).flatMap((item) => {
78
80
  if (!item.isDirectory()) return [];
@@ -83,7 +85,12 @@ export function discoverLocalCapabilities(
83
85
  return [];
84
86
  }
85
87
  const name = readSkillName(path);
86
- return name && !isPackageManagedSkill(name) ? [registerDiscoveredCapability(workspaceDir, profile, {
88
+ const reserved = reservedSkillName(name, path);
89
+ if (reserved) {
90
+ reservedSkills.push({ name: reserved, path, reason: 'reserved_skill_name' });
91
+ return [];
92
+ }
93
+ return name ? [registerDiscoveredCapability(workspaceDir, profile, {
87
94
  type: 'skill',
88
95
  path,
89
96
  runtimeId: name,
@@ -95,6 +102,6 @@ export function discoverLocalCapabilities(
95
102
  return {
96
103
  behaviors: behaviors.map(({ source, entry }) => ({ source: behaviorOperationName(source, entry), entry })),
97
104
  perceptions: perceptions.map(({ source, entry }) => ({ source: perceptionOperationName(source, entry), entry })),
98
- personas, skills,
105
+ personas, skills, reservedSkills,
99
106
  };
100
107
  }
@@ -1,5 +1,7 @@
1
1
  import type { AuthProfile } from './auth.js';
2
2
  import { HubClient } from './hub-client.js';
3
+ import { reservedSkillName } from './package-skills.js';
4
+ import { CommandOutputError } from './command-error.js';
3
5
  import { assignCapabilityOperationName, capabilitySelectionRef,
4
6
  readCapabilityWorkspaceRegistry, writeCapabilityWorkspaceRegistry,
5
7
  type CapabilityWorkspaceType } from './capability-workspace.js';
@@ -27,6 +29,11 @@ export async function selectCapability(
27
29
  if (matches.length !== 1) throw new Error(`capability_selection_${matches.length ? 'ambiguous' : 'not_found'}:${type}:${id}`);
28
30
  const entry = matches[0]!;
29
31
  if (type === 'skill' && equipped) {
32
+ const skill = skillNameCandidate(workspaceDir, profile, entry);
33
+ const reserved = reservedSkillName(entry.runtimeId) ?? reservedSkillName(skill.name, skill.working_copy_path);
34
+ if (reserved) throw new CommandOutputError(`reserved_skill_name:${reserved}`, {
35
+ error: 'reserved_skill_name', name: reserved, path: skill.working_copy_path, retryable: false,
36
+ });
30
37
  const candidates = Object.values(registry.entries).filter(other => other.type === 'skill'
31
38
  && (other.key === entry.key || (other.selection === 'equipped' && !other.hub?.cloudStatus)));
32
39
  const conflict = skillNameConflicts(candidates.map(other => skillNameCandidate(workspaceDir, profile, other)))
@@ -1,4 +1,14 @@
1
+ import { basename } from 'node:path';
2
+
1
3
  /** Package-owned teaching skills are independent of an account's Hub loadout. */
4
+ export const PACKAGE_MANAGED_SKILL_NAMES = ['clawclaw', 'clawclaw-creator'] as const;
5
+
6
+ export function reservedSkillName(name: string | null, directory?: string): string | undefined {
7
+ const key = name?.trim().toLowerCase();
8
+ const folder = directory && basename(directory).trim().toLowerCase();
9
+ return PACKAGE_MANAGED_SKILL_NAMES.find(reserved => reserved === key || reserved === folder);
10
+ }
11
+
2
12
  export function isPackageManagedSkill(name: string | null): boolean {
3
- return name === 'clawclaw' || name === 'clawclaw-creator';
13
+ return reservedSkillName(name) !== undefined;
4
14
  }
@@ -1,9 +1,14 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import type { ClawclawResolvedResourceMetadata } from '../../sdk/behavior-plugin/index.js';
1
3
  import type { Runtime } from '../framework/runtime.js';
2
4
  import type { OwnerControlResponse } from '../owner-control.js';
3
5
  import type { ClawclawBehaviorPlugin } from './plugins/behavior/behavior-plugin.js';
4
6
 
5
7
  type StartRuntime = Pick<Runtime, 'publicScope' | 'currentSegment' | 'readState'>;
6
8
  type BehaviorStarter = Pick<ClawclawBehaviorPlugin, 'startLong' | 'startShort'>;
9
+ type DeferredStartRuntime = StartRuntime & Pick<Runtime, 'diagnostic'> & {
10
+ readReadyView(): Pick<ReturnType<Runtime['readReadyView']>, 'state'>;
11
+ };
7
12
 
8
13
  interface BehaviorStartRequest {
9
14
  expectedScope: Readonly<{ sessionId: string; segmentId: string }>;
@@ -50,10 +55,14 @@ export async function startOwnerBehavior(
50
55
  runtime: StartRuntime,
51
56
  behavior: BehaviorStarter,
52
57
  request: BehaviorStartRequest,
58
+ canStart: () => boolean = () => true,
53
59
  ): Promise<OwnerControlResponse> {
54
60
  let rejection: OwnerControlResponse | undefined;
55
61
  const isCurrent = (): boolean => {
56
62
  rejection = startRejection(runtime, request);
63
+ if (!rejection && !canStart()) {
64
+ rejection = { ok: false, type: 'behavior_start', error: 'deferred_strategy_not_ready' };
65
+ }
57
66
  return rejection === undefined;
58
67
  };
59
68
  if (!isCurrent()) return rejection!;
@@ -77,3 +86,108 @@ export async function startOwnerBehavior(
77
86
  };
78
87
  }
79
88
  }
89
+
90
+ /** One explicit short selection per game. GAR still owns actual activations. */
91
+ export class DeferredMeetingShortStrategy {
92
+ private requestVersion = 0;
93
+ private pending?: {
94
+ request: BehaviorStartRequest;
95
+ requestId: string;
96
+ display: ClawclawResolvedResourceMetadata;
97
+ starting: boolean;
98
+ };
99
+
100
+ constructor(
101
+ private readonly runtime: DeferredStartRuntime,
102
+ private readonly behavior: BehaviorStarter & Pick<ClawclawBehaviorPlugin, 'cancel'>,
103
+ private readonly resolveDisplay: (request: BehaviorStartRequest) => ClawclawResolvedResourceMetadata | undefined,
104
+ ) {}
105
+
106
+ async start(request: BehaviorStartRequest): Promise<OwnerControlResponse> {
107
+ const rejection = startRejection(this.runtime, request);
108
+ if (rejection) return rejection;
109
+ if (request.layer !== 'short') return startOwnerBehavior(this.runtime, this.behavior, request);
110
+ const version = ++this.requestVersion;
111
+ const inMeeting = () => this.runtime.readState().state?.phase === 'meeting';
112
+ if (!inMeeting()) {
113
+ this.pending = undefined;
114
+ const result = await startOwnerBehavior(this.runtime, this.behavior, request,
115
+ () => version === this.requestVersion && !inMeeting());
116
+ if (version !== this.requestVersion || result.error !== 'deferred_strategy_not_ready' || !inMeeting()) return result;
117
+ const latestRejection = startRejection(this.runtime, request);
118
+ if (latestRejection) return latestRejection;
119
+ }
120
+ try {
121
+ const display = this.resolveDisplay(request);
122
+ if (!display) return { ok: false, type: 'behavior_start', error: 'behavior_not_found' };
123
+ this.pending = { request: structuredClone(request), requestId: randomUUID(), display, starting: false };
124
+ return { ok: true, type: 'behavior_start', status: 'queued', pending: this.status() };
125
+ } catch (error) {
126
+ return { ok: false, type: 'behavior_start', error: error instanceof Error ? error.message : String(error) };
127
+ }
128
+ }
129
+
130
+ status(behaviorId?: string) {
131
+ const pending = this.currentPending();
132
+ if (!pending || (behaviorId && pending.request.behavior !== behaviorId)) return undefined;
133
+ return {
134
+ request_id: pending.requestId, behavior: pending.request.behavior, layer: 'short' as const,
135
+ status: pending.starting ? 'starting' : 'waiting_for_wandering',
136
+ };
137
+ }
138
+
139
+ display(): ClawclawResolvedResourceMetadata | undefined {
140
+ return this.currentPending()?.display;
141
+ }
142
+
143
+ cancel(requestId: string): boolean {
144
+ if (this.currentPending()?.requestId !== requestId) return false;
145
+ this.pending = undefined;
146
+ return true;
147
+ }
148
+
149
+ afterReady(): void {
150
+ const pending = this.currentPending();
151
+ if (!pending || pending.starting || this.runtime.readState().state?.phase !== 'wandering'
152
+ || this.runtime.readReadyView().state.state?.phase !== 'wandering') return;
153
+ pending.starting = true;
154
+ void this.activate(pending).catch(error => {
155
+ this.runtime.diagnostic('behavior.deferred_short.failed', {
156
+ behavior_id: pending.request.behavior,
157
+ error: error instanceof Error ? error.message : String(error),
158
+ }, 'warn');
159
+ });
160
+ }
161
+
162
+ private currentPending() {
163
+ const pending = this.pending;
164
+ if (!pending) return undefined;
165
+ const rejection = startRejection(this.runtime, pending.request);
166
+ if (rejection && rejection.code !== 'GAME_STATE_UNAVAILABLE') {
167
+ this.pending = undefined;
168
+ return undefined;
169
+ }
170
+ return pending;
171
+ }
172
+
173
+ private async activate(pending: NonNullable<DeferredMeetingShortStrategy['pending']>): Promise<void> {
174
+ const canStart = () => this.pending === pending && this.runtime.readState().state?.phase === 'wandering';
175
+ const result = await startOwnerBehavior(this.runtime, this.behavior, pending.request, canStart);
176
+ if (this.pending !== pending) {
177
+ // Cancellation or replacement can arrive while the new runner starts.
178
+ const activationId = result.ok && result.activation?.activationId;
179
+ if (typeof activationId === 'string') await this.behavior.cancel(activationId, 'deferred_short_superseded');
180
+ return;
181
+ }
182
+ if (result.error === 'deferred_strategy_not_ready' || result.code === 'GAME_STATE_UNAVAILABLE') {
183
+ pending.starting = false;
184
+ return;
185
+ }
186
+ this.pending = undefined;
187
+ if (!result.ok) {
188
+ this.runtime.diagnostic('behavior.deferred_short.failed', {
189
+ behavior_id: pending.request.behavior, error: result.error,
190
+ }, 'warn');
191
+ }
192
+ }
193
+ }
@@ -5,7 +5,8 @@ import { createClawclawProcessingCadence } from './runtime-cadence.js';
5
5
  import { readRuntimeCycleIntervalMs } from '../../lib/runtime-cadence-config.js';
6
6
  import { randomUUID } from 'node:crypto';
7
7
  import { BehaviorReflexControl } from './behavior-reflex-control.js';
8
- import { startOwnerBehavior } from './behavior-start-control.js';
8
+ import { DeferredMeetingShortStrategy } from './behavior-start-control.js';
9
+ import { normalizeBehaviorInput } from './behavior-input-fields.js';
9
10
  import { acquireOwnerLock, type OwnerLock } from './owner-lock.js';
10
11
  import { createStartingOwnerControl } from './starting-owner-control.js';
11
12
  export { acquireOwnerLock, type OwnerLock, type OwnerLockOperations } from './owner-lock.js';
@@ -671,6 +672,13 @@ export async function runClawclawOwner(
671
672
  behaviorEventTypes: assembly.behavior.produces?.events ?? [],
672
673
  perceptionEventTypes: assembly.modules?.produces.events,
673
674
  });
675
+ const deferredShort = new DeferredMeetingShortStrategy(runtime, assembly.behavior, request => {
676
+ const source = behaviorSourceById.get(request.behavior);
677
+ if (!source) return undefined;
678
+ normalizeBehaviorInput(request.input, source.inputs, { allowedKeys: ['timeout_ms', 'duration_ms'] });
679
+ return resolveClawclawResourceMetadata(source, 'zh-CN');
680
+ });
681
+ assembly.behavior.attachDeferredShortControl(deferredShort);
674
682
  if (fullDiagnosticsEnabled) {
675
683
  processTimingSampler = new RuntimeProcessTimingSampler();
676
684
  const sample = (): void => {
@@ -1225,7 +1233,7 @@ export async function runClawclawOwner(
1225
1233
  || maxRuntimeMs > 120_000
1226
1234
  ))
1227
1235
  ) return { ok: false, type: 'behavior_start', error: 'invalid_behavior_start_request' };
1228
- return startOwnerBehavior(runtime!, assembly.behavior, {
1236
+ return deferredShort.start({
1229
1237
  expectedScope: expected,
1230
1238
  behavior,
1231
1239
  layer,
@@ -1234,7 +1242,11 @@ export async function runClawclawOwner(
1234
1242
  });
1235
1243
  }
1236
1244
  if (request.type === 'behavior_status') {
1237
- return { ok: true, type: 'behavior_status', status: reflexControl.view(typeof request.behavior === 'string' ? request.behavior : undefined) };
1245
+ const id = typeof request.behavior === 'string' ? request.behavior : undefined;
1246
+ const pending = deferredShort.status(id);
1247
+ return { ok: true, type: 'behavior_status', status: {
1248
+ ...reflexControl.view(id), ...(pending ? { pending_short: pending } : {}),
1249
+ } };
1238
1250
  }
1239
1251
  if (request.type === 'behavior_cancel') {
1240
1252
  const expected = ownerExpectedScope(request.expected_scope);
@@ -1244,7 +1256,10 @@ export async function runClawclawOwner(
1244
1256
  }
1245
1257
  const requestedId = typeof request.activation_id === 'string'
1246
1258
  ? request.activation_id.trim()
1247
- : assembly.behavior.status().current?.activationId;
1259
+ : assembly.behavior.status().current?.activationId ?? deferredShort.status()?.request_id;
1260
+ if (requestedId && deferredShort.cancel(requestedId)) {
1261
+ return { ok: true, type: 'behavior_cancel', cancelled: true, request_id: requestedId };
1262
+ }
1248
1263
  if (!requestedId) {
1249
1264
  return { ok: true, type: 'behavior_cancel', cancelled: false };
1250
1265
  }
@@ -11,6 +11,7 @@ import type { ClawclawBehaviorObservationSnapshot } from '../../behavior-observa
11
11
  // This entry point only adapts the game SDK and verifies the pinned source.
12
12
  await runStrategyWorker<ResolvedClawclawBehaviorSource, BehaviorInput, BehaviorDecision, BehaviorReadApi, ClawclawBehaviorObservationSnapshot>({
13
13
  async load(data) {
14
+ resolveBehaviorSource(data.source);
14
15
  const module = await import(data.sourceUrl) as Record<string, unknown>;
15
16
  resolveBehaviorSource(data.source);
16
17
  const loaded = validateClawclawBehaviorModule(module, data.source);
@@ -98,17 +98,22 @@ export class ClawclawBehaviorCatalog {
98
98
  return loading;
99
99
  }
100
100
 
101
- async prepare(id: string, input: unknown): Promise<PreparedClawclawBehavior> {
101
+ prepareForActivation(id: string, input: unknown, diagnosticsEnabled = false): Promise<PreparedClawclawBehavior> {
102
+ return this.prepare(id, input, true, diagnosticsEnabled);
103
+ }
104
+
105
+ async prepare(id: string, input: unknown, retainWorker = false, diagnosticsEnabled = false): Promise<PreparedClawclawBehavior> {
102
106
  const source = this.sources.get(id);
103
107
  if (!source) throw new Error(`Unknown behavior module '${id}'.`);
104
- const prepared = await prepareBehaviorInWorker(
105
- source,
106
- input as Readonly<Record<string, unknown>>,
107
- );
108
+ const rawInput = deepFreezeBehaviorValue(normalizeBehaviorInput(input, source.inputs, { allowedKeys: ['timeout_ms', 'duration_ms'] }));
109
+ const prepared = await prepareBehaviorInWorker(source, input as Readonly<Record<string, unknown>>, {
110
+ retainWorker, diagnosticsEnabled,
111
+ });
108
112
  return Object.freeze({
109
113
  manifest: deepFreezeBehaviorValue(structuredClone(prepared.manifest)),
110
114
  input: deepFreezeBehaviorValue(structuredClone(prepared.input)),
111
- rawInput: deepFreezeBehaviorValue(normalizeBehaviorInput(input, source.inputs, { allowedKeys: ['timeout_ms', 'duration_ms'] })),
115
+ rawInput,
116
+ ...(prepared.worker ? { worker: prepared.worker } : {}),
112
117
  source: prepared.source,
113
118
  display: source.display,
114
119
  ...(prepared.timing === undefined ? {} : { timing: prepared.timing }),
@@ -1,5 +1,6 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { readFileSync, readdirSync, realpathSync, statSync } from 'node:fs';
3
+ import * as asyncFs from 'node:fs/promises';
3
4
  import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
4
5
  import { pathToFileURL } from 'node:url';
5
6
  import {
@@ -197,9 +198,55 @@ export function pinBehaviorSource(
197
198
  });
198
199
  }
199
200
 
201
+ /** Pin source before dispatch without making the Owner wait on synchronous disk reads. */
202
+ export async function pinBehaviorSourceAsync(source: ResolvedClawclawBehaviorSource): Promise<ResolvedClawclawBehaviorSource> {
203
+ const sourceRoot = await asyncFs.realpath(source.sourceRoot);
204
+ const sourcePath = await asyncFs.realpath(source.sourcePath);
205
+ if (!pathInside(sourceRoot, sourcePath) || dirname(sourcePath) !== sourceRoot
206
+ || !(await asyncFs.stat(sourcePath)).isFile()) {
207
+ throw new Error(`Behavior '${source.id}' source is outside its root.`);
208
+ }
209
+ const files: Array<{ path: string; relativePath: string }> = [];
210
+ const visit = async (directory: string): Promise<void> => {
211
+ for (const entry of await asyncFs.readdir(directory, { withFileTypes: true })) {
212
+ const path = join(directory, entry.name);
213
+ if (entry.isSymbolicLink()) throw new Error('behavior_source_tree_symlink_unsupported');
214
+ if (entry.isDirectory()) await visit(path);
215
+ else if (entry.isFile() && RUNTIME_SOURCE_FILE.test(entry.name)) {
216
+ if (files.length >= MAX_BEHAVIOR_SOURCE_TREE_FILES) throw new Error('behavior_source_tree_file_limit_exceeded');
217
+ const physical = await asyncFs.realpath(path);
218
+ if (!pathInside(sourceRoot, physical)) throw new Error('behavior_source_tree_outside_root');
219
+ files.push({ path: physical, relativePath: relative(sourceRoot, physical).replaceAll('\\', '/') });
220
+ }
221
+ }
222
+ };
223
+ await visit(sourceRoot);
224
+ files.sort((left, right) => left.relativePath.localeCompare(right.relativePath));
225
+ const hash = createHash('sha256');
226
+ let totalBytes = 0;
227
+ for (const file of files) {
228
+ if (totalBytes + (await asyncFs.stat(file.path)).size > MAX_BEHAVIOR_SOURCE_TREE_BYTES) {
229
+ throw new Error('behavior_source_tree_byte_limit_exceeded');
230
+ }
231
+ const content = await asyncFs.readFile(file.path);
232
+ totalBytes += content.length;
233
+ if (totalBytes > MAX_BEHAVIOR_SOURCE_TREE_BYTES) throw new Error('behavior_source_tree_byte_limit_exceeded');
234
+ if (file.path === sourcePath && source.trustedSourceSha256 !== undefined
235
+ && createHash('sha256').update(content).digest('hex') !== source.trustedSourceSha256) {
236
+ throw new Error('behavior_trusted_source_changed');
237
+ }
238
+ hash.update(file.relativePath).update('\0').update(content).update('\0');
239
+ }
240
+ const digest = hash.digest('hex');
241
+ if (source.trustedSourceTreeSha256 !== undefined && source.trustedSourceTreeSha256 !== digest) {
242
+ throw new Error('behavior_source_tree_changed');
243
+ }
244
+ return Object.freeze({ ...source, sourceRoot, sourcePath, trustedSourceTreeSha256: digest });
245
+ }
246
+
200
247
  /** Resolves one already-scanned source to the URL imported inside each Worker slot. */
201
248
  export function behaviorSourceUrl(source: ResolvedClawclawBehaviorSource): string {
202
- const resolved = resolveBehaviorSource(source);
249
+ const resolved = source;
203
250
  assertPluginApiVersion(
204
251
  'behavior_api_version_unsupported',
205
252
  BEHAVIOR_PLUGIN_API_VERSION,
@@ -5,6 +5,7 @@ import type {
5
5
  ClawclawBehaviorClass,
6
6
  ClawclawBehaviorManifest,
7
7
  } from '../../../../sdk/behavior-plugin/index.js';
8
+ import type { StrategyWorkerLease } from '@myclaw163/game-agent-runtime/strategy/thread-strategy-executor.js';
8
9
  import { normalizeBehaviorInput } from '../../behavior-input-fields.js';
9
10
  import { deepFreezeBehaviorValue } from './behavior-manifest.js';
10
11
  import type { ResolvedClawclawBehaviorSource } from './behavior-source.js';
@@ -24,6 +25,7 @@ export interface PreparedClawclawBehavior {
24
25
  readonly rawInput?: Readonly<Record<string, unknown>>;
25
26
  /** Static source identity required only by isolated parallel execution. */
26
27
  readonly source?: ResolvedClawclawBehaviorSource;
28
+ readonly worker?: StrategyWorkerLease;
27
29
  /** Present only when the request/module materialized a finite budget. */
28
30
  readonly timing?: Readonly<BehaviorTiming>;
29
31
  }
@@ -59,7 +59,7 @@ function isSuccessfulBackendStrategyReport(value: unknown): boolean {
59
59
  }
60
60
  export interface ClawclawBehaviorPluginOptions {
61
61
  readonly memory?: ClawclawStrategyMemory;
62
- readonly catalog: Pick<ClawclawBehaviorCatalog, 'has' | 'prepare'>;
62
+ readonly catalog: Pick<ClawclawBehaviorCatalog, 'has' | 'prepare'> & Partial<Pick<ClawclawBehaviorCatalog, 'prepareForActivation'>>;
63
63
  readonly fallbackBehaviors?: ClawclawRoleFallbackBehaviors;
64
64
  readonly manager?: BehaviorActivationManager;
65
65
  readonly driver?: ClawclawBehaviorControlDriver;
@@ -87,7 +87,7 @@ function sdkFrame(frame: StrategyFrame): Readonly<BehaviorInput> { return frame.
87
87
  function preparedValue(prepared: PreparedStrategy): PreparedClawclawBehavior {
88
88
  return { ...(prepared.value as PreparedClawclawBehavior), ...(prepared.module ? { module: prepared.module as PreparedClawclawBehavior['module'] } : {}) };
89
89
  }
90
- function createAdapter(): StrategyAdapter {
90
+ function createAdapter(deferredDisplay: () => ClawclawResolvedResourceMetadata | undefined, useAdaptiveWorkers: boolean): StrategyAdapter {
91
91
  const observations = new ClawclawBehaviorObservationMemory();
92
92
  return {
93
93
  input: (input, parameters, continuation, history) => {
@@ -116,6 +116,7 @@ function createAdapter(): StrategyAdapter {
116
116
  observations: { capture: frame => observations.capture(sdkFrame(frame)), snapshot: id => observations.snapshot(id), clear: () => observations.clear() },
117
117
  createRunner: options => {
118
118
  const runner = new ClawclawBehaviorRunner({ ...options, prepared: preparedValue(options.prepared),
119
+ initialWorkers: useAdaptiveWorkers ? 1 : undefined,
119
120
  memory: options.memory && ((input, active) => options.memory!({ value: input, epochId: input.epochId, scope: input.scope,
120
121
  nowMs: input.nowMs, tick: Number(input.gameState.tick ?? input.epochId), cycle: input.cycle, events: input.events }, active)) });
121
122
  return { execution: runner.execution, everyTicks: runner.everyTicks, prepare: () => runner.prepare(),
@@ -124,8 +125,9 @@ function createAdapter(): StrategyAdapter {
124
125
  decideParallel: (frame, signal, observation) => runner.decideParallel(sdkFrame(frame), signal, observation as ClawclawBehaviorObservationSnapshot) };
125
126
  },
126
127
  action: (action, epoch, safety, generation, tick) => ({ ...normalizeClawclawBehaviorAction(action as GameAction, epoch, safety, generation, tick) }),
127
- display: prepared => prepared ? resolveClawclawResourceMetadata({ ...preparedValue(prepared).manifest, display: prepared.display }, BACKEND_STRATEGY_REPORT_LOCALE)
128
- : { id: 'clawclaw:no-active-behavior', name: '无策略在运行', description: '当前没有活跃的策略。' },
128
+ display: prepared => deferredDisplay() ?? (prepared
129
+ ? resolveClawclawResourceMetadata({ ...preparedValue(prepared).manifest, display: prepared.display }, BACKEND_STRATEGY_REPORT_LOCALE)
130
+ : { id: 'clawclaw:no-active-behavior', name: '无策略在运行', description: '当前没有活跃的策略。' }),
129
131
  reportEligible: input => {
130
132
  const state = input.epoch.state;
131
133
  return isClawclawRuntimeState(state)
@@ -147,13 +149,33 @@ function createAdapter(): StrategyAdapter {
147
149
  };
148
150
  }
149
151
  /** Game policy and SDK adapter; activation/control/decision execution belongs to the shared runtime. */
152
+ interface DeferredShortControl {
153
+ display(): ClawclawResolvedResourceMetadata | undefined;
154
+ afterReady(): void;
155
+ }
156
+
150
157
  export class ClawclawBehaviorPlugin extends StrategyHost {
158
+ private readonly deferredShort: { control?: DeferredShortControl };
159
+
151
160
  constructor(options: ClawclawBehaviorPluginOptions) {
161
+ const deferredShort: { control?: DeferredShortControl } = {};
152
162
  super({ ...options, id: CLAWCLAW_BEHAVIOR_PLUGIN_ID, stateTopic: CLAWCLAW_BEHAVIOR_STATE_TOPIC,
153
- actionCapability: CLAWCLAW_ACTION_CAPABILITY, adapter: createAdapter(), captureActions: resolveDetailCapture().actions,
163
+ actionCapability: CLAWCLAW_ACTION_CAPABILITY, adapter: createAdapter(() => deferredShort.control?.display(), !!options.catalog.prepareForActivation), captureActions: resolveDetailCapture().actions,
154
164
  catalog: { has: id => options.catalog.has(id), prepare: async (id, input) => {
155
165
  const prepared = await options.catalog.prepare(id, input);
156
166
  return { ...prepared, value: prepared };
157
- } }, after: options.after ?? [CLAWCLAW_ACTION_PLUGIN_ID, CLAWCLAW_GAME_QUERY_PLUGIN_ID, CLAWCLAW_PERCEPTION_PLUGIN_ID, CLAWCLAW_TRIGGER_PLUGIN_ID] });
167
+ }, ...(options.catalog.prepareForActivation ? { prepareForActivation: async (id: string, input: Readonly<Record<string, unknown>>) => {
168
+ const prepared = await options.catalog.prepareForActivation!(id, input, options.diagnosticsEnabled);
169
+ return { ...prepared, value: prepared, discardWorker: () => prepared.worker?.dispose() };
170
+ } } : {}) }, after: options.after ?? [CLAWCLAW_ACTION_PLUGIN_ID, CLAWCLAW_GAME_QUERY_PLUGIN_ID, CLAWCLAW_PERCEPTION_PLUGIN_ID, CLAWCLAW_TRIGGER_PLUGIN_ID] });
171
+ this.deferredShort = deferredShort;
172
+ }
173
+
174
+ attachDeferredShortControl(control: DeferredShortControl): void {
175
+ this.deferredShort.control = control;
176
+ }
177
+
178
+ afterReady(): void {
179
+ this.deferredShort.control?.afterReady();
158
180
  }
159
181
  }
@@ -1,8 +1,30 @@
1
+ import { existsSync } from 'node:fs';
1
2
  import type { StrategyThreadBridge } from '@myclaw163/game-agent-runtime/strategy/thread-strategy-executor.js';
2
- import { behaviorSourceUrl, behaviorThreadLoaderConfig, pinBehaviorSource, resolveBehaviorSource } from './behavior-module-loader.js';
3
+ import { behaviorSourceUrl, behaviorThreadLoaderConfig, pinBehaviorSource, pinBehaviorSourceAsync } from './behavior-module-loader.js';
3
4
  import type { ResolvedClawclawBehaviorSource } from './behavior-source.js';
5
+ const compiled = new URL('../../../../../dist/strategy-worker/runtime/clawclaw/plugins/behavior/', import.meta.url);
6
+ const compiledHost = new URL('host.js', compiled);
7
+ const useCompiledWorker = existsSync(compiledHost);
8
+
9
+ function workerLoader() {
10
+ const loader = behaviorThreadLoaderConfig();
11
+ if (!useCompiledWorker) return loader;
12
+ const sdkAliases = Object.fromEntries(Object.entries(loader.sdkAliases).map(([specifier, target]) => {
13
+ if (!specifier.startsWith('clawclaw-cli') && !specifier.startsWith('@myclaw163/clawclaw-cli')) {
14
+ return [specifier, target];
15
+ }
16
+ const entry = /\/sdk\/([^/]+)\/index\.ts$/.exec(target)?.[1] ?? 'sdk';
17
+ return [specifier, new URL(`sdk-${entry}.js`, compiled).href];
18
+ }));
19
+ return { ...loader, sdkAliases };
20
+ }
21
+
4
22
  /** Game SDK and source validation; pool scheduling belongs to the framework. */
5
23
  export const CLAWCLAW_STRATEGY_WORKER_BRIDGE: StrategyThreadBridge<ResolvedClawclawBehaviorSource> = {
6
- hostUrl: new URL('./behavior-analysis-thread-host.ts', import.meta.url).href,
7
- pin: pinBehaviorSource, resolve: resolveBehaviorSource, sourceUrl: behaviorSourceUrl, loader: behaviorThreadLoaderConfig,
24
+ hostUrl: useCompiledWorker ? compiledHost.href : new URL('./behavior-analysis-thread-host.ts', import.meta.url).href,
25
+ pin: source => source.trustedSourceTreeSha256 ? source : pinBehaviorSource(source),
26
+ pinAsync: pinBehaviorSourceAsync,
27
+ resolve: source => source,
28
+ sourceUrl: behaviorSourceUrl,
29
+ loader: workerLoader,
8
30
  };