@myclaw163/clawclaw-cli 0.8.6 → 0.8.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,182 @@
1
+ import {
2
+ existsSync,
3
+ readFileSync,
4
+ readdirSync,
5
+ realpathSync,
6
+ statSync,
7
+ } from 'node:fs';
8
+ import {
9
+ basename,
10
+ dirname,
11
+ isAbsolute,
12
+ join,
13
+ relative,
14
+ } from 'node:path';
15
+
16
+ export type ModuleCapabilityType = 'behavior' | 'perception' | 'trigger';
17
+ export type CapabilitySource = 'hub' | 'local';
18
+
19
+ export type StaticModuleFailureReason =
20
+ | 'projection_missing'
21
+ | 'file_unreadable'
22
+ | 'source_too_large'
23
+ | 'public_sdk_import_required'
24
+ | 'default_export_missing'
25
+ | 'manifest_missing'
26
+ | 'static_manifest_invalid';
27
+
28
+ export interface StaticModuleDiagnostic {
29
+ readonly reason: StaticModuleFailureReason;
30
+ readonly path: string;
31
+ readonly file: string;
32
+ readonly declaredId?: string;
33
+ readonly declaredName?: string;
34
+ readonly expectedImport?: string;
35
+ readonly receivedImports?: readonly string[];
36
+ }
37
+
38
+ export interface CapabilityLoadWarning {
39
+ readonly code: 'CAPABILITY_NOT_LOADED';
40
+ readonly capability_type: 'behavior' | 'perception' | 'trigger' | 'persona';
41
+ readonly source: CapabilitySource;
42
+ readonly reason: string;
43
+ readonly stage: 'projection' | 'static_discovery' | 'selection';
44
+ readonly resource_id?: string;
45
+ readonly version_id?: string;
46
+ readonly id?: string;
47
+ readonly name?: string;
48
+ readonly file?: string;
49
+ readonly path?: string | null;
50
+ readonly expected_import?: string;
51
+ readonly received_imports?: readonly string[];
52
+ }
53
+
54
+ const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
55
+ const MAX_MODULE_FILES = 512;
56
+ const IMPORT_SPECIFIER = /(?:\bfrom\s*|\bimport\s*)["']([^"']+)["']/g;
57
+ const DECLARED_ID = /\bid\s*:\s*["']([^"']+)["']/;
58
+ const DECLARED_NAME = /\bname\s*:\s*["']([^"']+)["']/;
59
+
60
+ const MODULE_CONTRACTS: Record<ModuleCapabilityType, {
61
+ readonly expectedImport: string;
62
+ readonly safeImport: RegExp;
63
+ readonly defaultClass: RegExp;
64
+ readonly manifest: RegExp;
65
+ }> = {
66
+ behavior: {
67
+ expectedImport: '@myclaw163/clawclaw-cli/behavior-plugin',
68
+ safeImport: /(?:@myclaw163\/clawclaw-cli|clawclaw-cli)\/behavior-plugin/,
69
+ defaultClass: /export\s+default\s+class(?:\s+[A-Za-z_$][\w$]*)?\s+extends\s+ClawclawBehavior/,
70
+ manifest: /\bstatic\s+(?:override\s+)?(?:readonly\s+)?manifest\s*=\s*\{/,
71
+ },
72
+ perception: {
73
+ expectedImport: '@myclaw163/clawclaw-cli/perception-plugin',
74
+ safeImport: /(?:@myclaw163\/clawclaw-cli|clawclaw-cli)\/perception-plugin/,
75
+ defaultClass: /export\s+default\s+class(?:\s+[A-Za-z_$][\w$]*)?\s+extends\s+(?:ClawclawPerception|ClawclawParallelPerception)/,
76
+ manifest: /\bstatic\s+(?:readonly\s+)?manifest\s*=\s*\{/,
77
+ },
78
+ trigger: {
79
+ expectedImport: '@myclaw163/clawclaw-cli/trigger-plugin',
80
+ safeImport: /(?:@myclaw163\/clawclaw-cli|clawclaw-cli)\/trigger-plugin|[./]trigger-plugin(?:\.[cm]?[jt]s)?["']/,
81
+ defaultClass: /export\s+default\s+class(?:\s+[A-Za-z_$][\w$]*)?\s+extends\s+ClawclawTrigger/,
82
+ manifest: /\bstatic\s+(?:override\s+)?(?:readonly\s+)?manifest\s*=\s*\{/,
83
+ },
84
+ };
85
+
86
+ function pathInside(root: string, candidate: string): boolean {
87
+ const child = relative(root, candidate);
88
+ return child === '' || (!child.startsWith('..') && !isAbsolute(child));
89
+ }
90
+
91
+ export function listCapabilityModuleCandidates(directory: string): readonly string[] {
92
+ if (!existsSync(directory)) return [];
93
+ try {
94
+ const root = realpathSync(directory);
95
+ return readdirSync(root)
96
+ .filter((file) => (
97
+ !file.startsWith('_')
98
+ && !file.endsWith('.d.ts')
99
+ && !file.endsWith('.test.ts')
100
+ && /\.(?:ts|js)$/.test(file)
101
+ ))
102
+ .sort()
103
+ .slice(0, MAX_MODULE_FILES)
104
+ .flatMap((file) => {
105
+ try {
106
+ const path = realpathSync(join(root, file));
107
+ return pathInside(root, path) && dirname(path) === root ? [path] : [];
108
+ } catch {
109
+ return [];
110
+ }
111
+ });
112
+ } catch {
113
+ return [];
114
+ }
115
+ }
116
+
117
+ export function diagnoseRejectedCapabilityModule(
118
+ type: ModuleCapabilityType,
119
+ path: string,
120
+ ): StaticModuleDiagnostic {
121
+ const contract = MODULE_CONTRACTS[type];
122
+ if (!existsSync(path)) {
123
+ return { reason: 'projection_missing', path, file: basename(path) };
124
+ }
125
+ let source: string;
126
+ try {
127
+ if (!statSync(path).isFile()) throw new Error('not_file');
128
+ source = readFileSync(path, 'utf8');
129
+ } catch {
130
+ return { reason: 'file_unreadable', path, file: basename(path) };
131
+ }
132
+ const declaredId = DECLARED_ID.exec(source)?.[1];
133
+ const declaredName = DECLARED_NAME.exec(source)?.[1];
134
+ const common = {
135
+ path,
136
+ file: basename(path),
137
+ ...(declaredId ? { declaredId } : {}),
138
+ ...(declaredName ? { declaredName } : {}),
139
+ };
140
+ if (Buffer.byteLength(source, 'utf8') > MAX_SOURCE_BYTES) {
141
+ return { ...common, reason: 'source_too_large' };
142
+ }
143
+ if (!contract.safeImport.test(source)) {
144
+ const receivedImports = [...source.matchAll(IMPORT_SPECIFIER)].map((match) => match[1]!);
145
+ return {
146
+ ...common,
147
+ reason: 'public_sdk_import_required',
148
+ expectedImport: contract.expectedImport,
149
+ ...(receivedImports.length === 0 ? {} : { receivedImports }),
150
+ };
151
+ }
152
+ if (!contract.defaultClass.test(source)) {
153
+ return { ...common, reason: 'default_export_missing' };
154
+ }
155
+ if (!contract.manifest.test(source)) {
156
+ return { ...common, reason: 'manifest_missing' };
157
+ }
158
+ return { ...common, reason: 'static_manifest_invalid' };
159
+ }
160
+
161
+ export function warningFromStaticDiagnostic(
162
+ type: ModuleCapabilityType,
163
+ source: CapabilitySource,
164
+ diagnostic: StaticModuleDiagnostic,
165
+ metadata: { readonly resourceId?: string; readonly versionId?: string } = {},
166
+ ): CapabilityLoadWarning {
167
+ return {
168
+ code: 'CAPABILITY_NOT_LOADED',
169
+ capability_type: type,
170
+ source,
171
+ reason: diagnostic.reason,
172
+ stage: diagnostic.reason === 'projection_missing' ? 'projection' : 'static_discovery',
173
+ ...(metadata.resourceId ? { resource_id: metadata.resourceId } : {}),
174
+ ...(metadata.versionId ? { version_id: metadata.versionId } : {}),
175
+ ...(diagnostic.declaredId ? { id: diagnostic.declaredId } : {}),
176
+ ...(diagnostic.declaredName ? { name: diagnostic.declaredName } : {}),
177
+ file: diagnostic.file,
178
+ path: diagnostic.path,
179
+ ...(diagnostic.expectedImport ? { expected_import: diagnostic.expectedImport } : {}),
180
+ ...(diagnostic.receivedImports ? { received_imports: diagnostic.receivedImports } : {}),
181
+ };
182
+ }
@@ -41,6 +41,7 @@ const GAMEPLAY_CONFIG_FIELDS = new Set([
41
41
  'disabled_perception_modules',
42
42
  'fallback_behaviors',
43
43
  'disabled_behaviors',
44
+ 'disabled_triggers',
44
45
  'idle_ms',
45
46
  'triggers',
46
47
  ]);
@@ -62,6 +63,7 @@ export interface GameplayConfig {
62
63
  disabled_perception_modules: string[];
63
64
  fallback_behaviors: GameplayFallbackBehaviors;
64
65
  disabled_behaviors: string[];
66
+ disabled_triggers: string[];
65
67
  idle_ms: number;
66
68
  triggers: GameplayTriggerConfigs;
67
69
  }
@@ -73,6 +75,7 @@ export function defaultGameplayConfig(): GameplayConfig {
73
75
  disabled_perception_modules: [],
74
76
  fallback_behaviors: { ...NPM_ROLE_FALLBACK_BEHAVIORS },
75
77
  disabled_behaviors: [],
78
+ disabled_triggers: [],
76
79
  idle_ms: DEFAULT_BEHAVIOR_IDLE_MS,
77
80
  triggers: {},
78
81
  };
@@ -165,6 +168,12 @@ export function parseGameplayConfig(value: unknown): GameplayConfig {
165
168
  root.disabled_behaviors,
166
169
  'user-data/gameplay.json disabled_behaviors',
167
170
  ),
171
+ disabled_triggers: hasOwn(root, 'disabled_triggers')
172
+ ? resourceIds(
173
+ root.disabled_triggers,
174
+ 'user-data/gameplay.json disabled_triggers',
175
+ )
176
+ : [],
168
177
  idle_ms: behaviorIdleMs(root.idle_ms),
169
178
  triggers: parseGameplayTriggerConfigs(root.triggers),
170
179
  };
@@ -231,6 +240,7 @@ function migrateLegacyGameplayConfig(root: Record<string, unknown>): GameplayCon
231
240
  ...legacyDisabledStrategies,
232
241
  ...legacyDisabledIntents,
233
242
  ],
243
+ disabled_triggers: hasOwn(root, 'disabled_triggers') ? root.disabled_triggers : [],
234
244
  idle_ms: migratedIdleMs(root),
235
245
  triggers: hasOwn(root, 'triggers') ? root.triggers : {},
236
246
  });
@@ -2,11 +2,7 @@ import { MAX_TRIGGER_RUNTIME_MS } from '../sdk/trigger-plugin/index.js';
2
2
 
3
3
  export type GameplayTriggerRearm = 'after_clear' | 'after_cooldown';
4
4
 
5
- /** New community Trigger modules are inert until explicitly enabled. */
6
- export const DEFAULT_GAMEPLAY_TRIGGER_ENABLED = false;
7
-
8
5
  export interface GameplayTriggerConfig {
9
- enabled?: boolean;
10
6
  input?: Record<string, unknown>;
11
7
  behavior?: string;
12
8
  behavior_input?: Record<string, unknown>;
@@ -25,7 +21,6 @@ export type GameplayTriggerConfigs = Record<string, GameplayTriggerConfig>;
25
21
  */
26
22
  export interface TriggerRegistrationOverride {
27
23
  readonly id: string;
28
- readonly enabled?: boolean;
29
24
  readonly input?: Readonly<Record<string, unknown>>;
30
25
  readonly behavior?: string;
31
26
  readonly behaviorInput?: Readonly<Record<string, unknown>>;
@@ -37,6 +32,8 @@ export interface TriggerRegistrationOverride {
37
32
 
38
33
  const RESOURCE_ID = /^[a-z0-9][a-z0-9._-]*$/;
39
34
  const TRIGGER_FIELDS = new Set([
35
+ // Legacy persisted field: accepted but deliberately ignored. Enablement is
36
+ // controlled only by gameplay.disabled_triggers.
40
37
  'enabled',
41
38
  'input',
42
39
  'behavior',
@@ -139,9 +136,6 @@ function parseTriggerConfig(value: unknown, field: string): GameplayTriggerConfi
139
136
  if (unknown.length > 0) {
140
137
  throw new Error(`${field} contains unknown fields: ${unknown.sort().join(', ')}.`);
141
138
  }
142
- if (source.enabled !== undefined && typeof source.enabled !== 'boolean') {
143
- throw new Error(`${field}.enabled must be a boolean.`);
144
- }
145
139
  if (
146
140
  source.behavior !== undefined
147
141
  && (typeof source.behavior !== 'string' || !RESOURCE_ID.test(source.behavior))
@@ -164,7 +158,6 @@ function parseTriggerConfig(value: unknown, field: string): GameplayTriggerConfi
164
158
  }
165
159
 
166
160
  return {
167
- ...(source.enabled === undefined ? {} : { enabled: source.enabled }),
168
161
  ...(source.input === undefined ? {} : { input: jsonObject(source.input, `${field}.input`) }),
169
162
  ...(source.behavior === undefined ? {} : { behavior: source.behavior }),
170
163
  ...(source.behavior_input === undefined ? {} : {
@@ -201,7 +194,6 @@ export function toTriggerRegistrationOverrides(
201
194
  const normalized = parseGameplayTriggerConfigs(configs);
202
195
  return Object.entries(normalized).map(([id, config]) => Object.freeze({
203
196
  id,
204
- ...(config.enabled === undefined ? {} : { enabled: config.enabled }),
205
197
  ...(config.input === undefined ? {} : { input: Object.freeze(config.input) }),
206
198
  ...(config.behavior === undefined ? {} : { behavior: config.behavior }),
207
199
  ...(config.behavior_input === undefined ? {} : {
@@ -20,6 +20,11 @@ function object(value: unknown): Record<string, any> | null {
20
20
  : null;
21
21
  }
22
22
 
23
+ function backendRoomOrFallback(item: Record<string, any>): string | null {
24
+ if (typeof item.room === 'string' && item.room.trim().length > 0) return item.room;
25
+ return resolveRoom({ x: item.x, y: item.y });
26
+ }
27
+
23
28
  interface PlayerRef {
24
29
  name: string;
25
30
  seat: number;
@@ -88,7 +93,7 @@ export class ObservationFrameProjector {
88
93
  : { alive: true }),
89
94
  x: item.x,
90
95
  y: item.y,
91
- room: resolveRoom({ x: item.x, y: item.y }),
96
+ room: backendRoomOrFallback(item),
92
97
  };
93
98
  }
94
99
 
@@ -109,7 +114,7 @@ export class ObservationFrameProjector {
109
114
  } : {}),
110
115
  x: item.x,
111
116
  y: item.y,
112
- room: resolveRoom({ x: item.x, y: item.y }),
117
+ room: backendRoomOrFallback(item),
113
118
  });
114
119
  }
115
120
  return corpses;
@@ -19,10 +19,7 @@ import {
19
19
  readGameplayConfig,
20
20
  type GameplayConfig,
21
21
  } from '../../lib/gameplay-config.js';
22
- import {
23
- DEFAULT_GAMEPLAY_TRIGGER_ENABLED,
24
- toTriggerRegistrationOverrides,
25
- } from '../../lib/trigger-config.js';
22
+ import { toTriggerRegistrationOverrides } from '../../lib/trigger-config.js';
26
23
  import {
27
24
  isRoomMode,
28
25
  isTrainingRoomMode,
@@ -292,7 +289,7 @@ export function roleFallbackBehaviors(
292
289
 
293
290
  export function triggerRegistrations(
294
291
  sources: readonly ResolvedClawclawTriggerSource[],
295
- config: Pick<GameplayConfig, 'triggers'>,
292
+ config: Pick<GameplayConfig, 'triggers' | 'disabled_triggers'>,
296
293
  catalog: Pick<ClawclawBehaviorCatalog, 'list'>,
297
294
  warning: ConfigurationWarning = () => {},
298
295
  ): readonly ClawclawTriggerRegistration[] {
@@ -302,6 +299,7 @@ export function triggerRegistrations(
302
299
  const overrides = new Map(
303
300
  toTriggerRegistrationOverrides(config.triggers).map((override) => [override.id, override]),
304
301
  );
302
+ const disabledTriggers = new Set(config.disabled_triggers);
305
303
  const sourceIds = new Set(sources.map((source) => source.id));
306
304
  for (const id of overrides.keys()) {
307
305
  if (!sourceIds.has(id)) warning('trigger_source_unavailable', { trigger_id: id });
@@ -309,7 +307,7 @@ export function triggerRegistrations(
309
307
  return Object.freeze(sources.map((source): ClawclawTriggerRegistration => {
310
308
  const override = overrides.get(source.id);
311
309
  const behavior = override?.behavior ?? source.manifest.defaultBehavior;
312
- const requestedEnabled = override?.enabled ?? DEFAULT_GAMEPLAY_TRIGGER_ENABLED;
310
+ const requestedEnabled = !disabledTriggers.has(source.id);
313
311
  const enabled = requestedEnabled
314
312
  && source.apiVersion === TRIGGER_PLUGIN_API_VERSION
315
313
  && loadableBehaviors.has(behavior);
@@ -1,4 +1,5 @@
1
1
  import { readFileSync } from 'fs';
2
+ import { inflateSync } from 'node:zlib';
2
3
  import type { VisualPosition } from './contracts.js';
3
4
  import { createSpatialApi, type SpatialFacts } from '../../spatial-api.js';
4
5
 
@@ -22,6 +23,15 @@ interface RawSpatialFacts {
22
23
  player_body: {
23
24
  body_length_px: number;
24
25
  };
26
+ room_lookup: {
27
+ encoding: 'row-major-zlib-uint8-v1';
28
+ width_tiles: number;
29
+ height_tiles: number;
30
+ tile_width_px: number;
31
+ tile_height_px: number;
32
+ room_names: string[];
33
+ data_base64: string;
34
+ };
25
35
  rooms: MapRoomArea[];
26
36
  room_transitions: SpatialTransition[];
27
37
  }
@@ -34,6 +44,19 @@ function loadSpatialFacts(): RawSpatialFacts {
34
44
  parsed.schema_version !== 2
35
45
  || parsed.coordinates?.x_positive !== 'right'
36
46
  || parsed.coordinates?.y_positive !== 'down'
47
+ || parsed.room_lookup?.encoding !== 'row-major-zlib-uint8-v1'
48
+ || !Number.isInteger(parsed.room_lookup.width_tiles)
49
+ || parsed.room_lookup.width_tiles <= 0
50
+ || !Number.isInteger(parsed.room_lookup.height_tiles)
51
+ || parsed.room_lookup.height_tiles <= 0
52
+ || !Number.isFinite(parsed.room_lookup.tile_width_px)
53
+ || parsed.room_lookup.tile_width_px <= 0
54
+ || !Number.isFinite(parsed.room_lookup.tile_height_px)
55
+ || parsed.room_lookup.tile_height_px <= 0
56
+ || !Array.isArray(parsed.room_lookup.room_names)
57
+ || parsed.room_lookup.room_names.length === 0
58
+ || typeof parsed.room_lookup.data_base64 !== 'string'
59
+ || parsed.room_lookup.data_base64.length === 0
37
60
  ) {
38
61
  throw new Error('Unsupported ClawClaw spatial facts');
39
62
  }
@@ -43,6 +66,21 @@ function loadSpatialFacts(): RawSpatialFacts {
43
66
  export const CLAWCLAW_SPATIAL_FACTS = loadSpatialFacts();
44
67
  export const PLAYER_BODY_LENGTH_PX = CLAWCLAW_SPATIAL_FACTS.player_body.body_length_px;
45
68
 
69
+ const RAW_ROOM_LOOKUP = CLAWCLAW_SPATIAL_FACTS.room_lookup;
70
+ const ROOM_LOOKUP_CELL_COUNT = RAW_ROOM_LOOKUP.width_tiles * RAW_ROOM_LOOKUP.height_tiles;
71
+ const ROOM_LOOKUP_BUFFER = inflateSync(Buffer.from(RAW_ROOM_LOOKUP.data_base64, 'base64'));
72
+ if (ROOM_LOOKUP_BUFFER.byteLength !== ROOM_LOOKUP_CELL_COUNT) {
73
+ throw new Error('Invalid ClawClaw room lookup size');
74
+ }
75
+ const ROOM_LOOKUP = new Uint8Array(
76
+ ROOM_LOOKUP_BUFFER.buffer,
77
+ ROOM_LOOKUP_BUFFER.byteOffset,
78
+ ROOM_LOOKUP_BUFFER.byteLength,
79
+ );
80
+ if (ROOM_LOOKUP.some((roomIndex) => roomIndex >= RAW_ROOM_LOOKUP.room_names.length)) {
81
+ throw new Error('Invalid ClawClaw room lookup index');
82
+ }
83
+
46
84
  const ROOM_BY_NAME = new Map(
47
85
  CLAWCLAW_SPATIAL_FACTS.rooms.map((room) => [room.name, room] as const),
48
86
  );
@@ -68,7 +106,17 @@ export function roomAt(x: number, y: number): MapRoomArea | null {
68
106
  }
69
107
 
70
108
  export function resolveRoom(position: Pick<VisualPosition, 'x' | 'y'>): string | null {
71
- return roomAt(position.x, position.y)?.name ?? null;
109
+ if (!Number.isFinite(position.x) || !Number.isFinite(position.y)) return null;
110
+ const tileX = Math.max(0, Math.min(
111
+ RAW_ROOM_LOOKUP.width_tiles - 1,
112
+ Math.floor(position.x / RAW_ROOM_LOOKUP.tile_width_px),
113
+ ));
114
+ const tileY = Math.max(0, Math.min(
115
+ RAW_ROOM_LOOKUP.height_tiles - 1,
116
+ Math.floor(position.y / RAW_ROOM_LOOKUP.tile_height_px),
117
+ ));
118
+ const roomIndex = ROOM_LOOKUP[tileY * RAW_ROOM_LOOKUP.width_tiles + tileX];
119
+ return RAW_ROOM_LOOKUP.room_names[roomIndex] ?? null;
72
120
  }
73
121
 
74
122
  export function sideInRoom(position: VisualPosition): string | null {