@myclaw163/clawclaw-cli 0.8.14 → 0.8.15

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 (44) 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/skills/clawclaw/SKILL.md +5 -1
  8. package/skills/clawclaw/references/BEHAVIORS.md +16 -1
  9. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +310 -0
  10. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +684 -0
  11. package/skills/clawclaw/references/CUSTOM-MODULES.md +125 -0
  12. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +331 -0
  13. package/src/runtime/clawclaw/behavior-decision.ts +4 -1
  14. package/src/runtime/clawclaw/owner.ts +64 -1
  15. package/src/runtime/clawclaw/plugins/assembly.ts +4 -0
  16. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +35 -2
  17. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +11 -7
  18. package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +3 -2
  19. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +46 -50
  20. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +39 -9
  21. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +167 -7
  22. package/src/runtime/clawclaw/plugins/perception/module-runner.ts +86 -89
  23. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.ts +157 -41
  24. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +28 -4
  25. package/src/runtime/clawclaw/plugins/perception/perception-module-loader.ts +3 -1
  26. package/src/runtime/clawclaw/plugins/perception/perception-module-output.ts +30 -0
  27. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +114 -17
  28. package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-pool.ts +660 -0
  29. package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-worker.ts +262 -0
  30. package/src/runtime/clawclaw/plugins/trigger/trigger-module-loader.ts +41 -12
  31. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +252 -20
  32. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-pool.ts +496 -0
  33. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-worker.ts +164 -0
  34. package/src/runtime/clawclaw-event-catalog.ts +1 -0
  35. package/src/runtime/framework/events/memory-event-repository.ts +12 -0
  36. package/src/runtime/framework/modules/runtime-module-output.ts +24 -0
  37. package/src/runtime/framework/persistence/memory-first-persistence.ts +3 -0
  38. package/src/runtime/framework/plugins/contracts.ts +3 -0
  39. package/src/runtime/framework/plugins/runtime-input-journal.ts +12 -0
  40. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +150 -23
  41. package/src/runtime/framework/runtime.ts +18 -0
  42. package/src/runtime/framework/state/history/memory-state-history-repository.ts +10 -0
  43. package/src/runtime/observability/redaction.ts +28 -1
  44. package/src/sdk/perception-plugin/index.ts +13 -8
@@ -0,0 +1,262 @@
1
+ import { parentPort, workerData } from 'node:worker_threads';
2
+ import {
3
+ PERCEPTION_PLUGIN_API_VERSION,
4
+ type ClawclawPerception,
5
+ type ClawclawPerceptionClass,
6
+ type PerceptionAnalysisInput,
7
+ type PerceptionBoundary,
8
+ type PerceptionFrame,
9
+ } from '../../../../sdk/perception-plugin/index.js';
10
+ import { createSpatialApi, type SpatialFacts } from '../../spatial-api.js';
11
+ import type { PerceptionThreadModuleSpec } from './perception-module-loader.js';
12
+ import { normalizePerceptionEvents } from './perception-module-output.js';
13
+ import { assertRuntimeModuleOutputSize } from '../../../framework/modules/runtime-module-output.js';
14
+
15
+ type ResetReason = Exclude<PerceptionBoundary['kind'], 'events_requested'> | 'replay';
16
+ type ReducerOperation = 'update' | 'commit' | 'flush' | 'reset';
17
+
18
+ interface PerceptionReducerWorkerData {
19
+ readonly poolId: string;
20
+ readonly laneId: number;
21
+ readonly modules: readonly PerceptionThreadModuleSpec[];
22
+ readonly spatialFacts: SpatialFacts;
23
+ readonly diagnosticsEnabled?: boolean;
24
+ }
25
+
26
+ interface PerceptionReducerRequest {
27
+ readonly type: 'operate';
28
+ readonly poolId: string;
29
+ readonly requestId: string;
30
+ readonly moduleId: string;
31
+ readonly operation: ReducerOperation;
32
+ readonly frame?: PerceptionFrame;
33
+ readonly analysis?: unknown;
34
+ readonly boundary?: PerceptionBoundary;
35
+ readonly reason?: ResetReason;
36
+ }
37
+
38
+ function deepFreeze<T>(value: T, seen = new WeakSet<object>()): T {
39
+ if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value;
40
+ const object = value as object;
41
+ if (seen.has(object)) return value;
42
+ seen.add(object);
43
+ for (const child of Object.values(object)) deepFreeze(child, seen);
44
+ return Object.freeze(value);
45
+ }
46
+
47
+ function errorMessage(error: unknown): string {
48
+ return error instanceof Error ? error.message : String(error);
49
+ }
50
+
51
+ function errorCode(error: unknown): string {
52
+ const message = errorMessage(error).trim();
53
+ return /^([A-Za-z][A-Za-z0-9_.-]{0,119})(?::|$)/.exec(message)?.[1]
54
+ ?? 'PERCEPTION_REDUCER_OPERATION_FAILED';
55
+ }
56
+
57
+ const port = parentPort;
58
+ if (!port) throw new Error('perception_reducer_worker_parent_missing');
59
+ const data = workerData as Partial<PerceptionReducerWorkerData> | undefined;
60
+ if (
61
+ !data
62
+ || typeof data.poolId !== 'string'
63
+ || !data.poolId
64
+ || typeof data.laneId !== 'number'
65
+ || !Array.isArray(data.modules)
66
+ || data.modules.length === 0
67
+ || !data.spatialFacts
68
+ || typeof data.spatialFacts !== 'object'
69
+ ) throw new Error('perception_reducer_worker_data_invalid');
70
+
71
+ function diagnosticMemory(): Readonly<Record<string, number>> {
72
+ return data?.diagnosticsEnabled === true
73
+ ? { heapUsedBytes: process.memoryUsage().heapUsed }
74
+ : {};
75
+ }
76
+
77
+ function send(value: Readonly<Record<string, unknown>>): void {
78
+ port!.postMessage({
79
+ ...value,
80
+ poolId: data!.poolId!,
81
+ laneId: data!.laneId!,
82
+ ...diagnosticMemory(),
83
+ });
84
+ }
85
+
86
+ function validateClass(
87
+ spec: PerceptionThreadModuleSpec,
88
+ loaded: Record<string, unknown>,
89
+ ): ClawclawPerceptionClass {
90
+ if (typeof loaded.default !== 'function') {
91
+ throw new Error('perception_reducer_worker_class_missing');
92
+ }
93
+ const ModuleClass = loaded.default as unknown as ClawclawPerceptionClass;
94
+ const manifest = ModuleClass.manifest;
95
+ if (
96
+ !manifest
97
+ || manifest.apiVersion !== PERCEPTION_PLUGIN_API_VERSION
98
+ || manifest.id !== spec.moduleId
99
+ || (manifest.execution ?? 'ordered_update')
100
+ !== (spec.manifest.execution ?? 'ordered_update')
101
+ || JSON.stringify(manifest.produces) !== JSON.stringify(spec.manifest.produces)
102
+ ) throw new Error('perception_reducer_worker_manifest_mismatch');
103
+ return ModuleClass;
104
+ }
105
+
106
+ function validateInstance(
107
+ spec: PerceptionThreadModuleSpec,
108
+ instance: ClawclawPerception,
109
+ ): void {
110
+ const execution = spec.manifest.execution ?? 'ordered_update';
111
+ if (
112
+ !instance
113
+ || typeof instance !== 'object'
114
+ || (execution === 'ordered_update' && typeof instance.update !== 'function')
115
+ || (execution === 'parallel_analysis' && (
116
+ typeof (instance as any).analyze !== 'function'
117
+ || typeof (instance as any).commit !== 'function'
118
+ ))
119
+ ) throw new Error('perception_reducer_worker_contract_invalid');
120
+ }
121
+
122
+ const api = Object.freeze({ spatial: createSpatialApi(data.spatialFacts) });
123
+ const specs = new Map<string, PerceptionThreadModuleSpec>();
124
+ const classes = new Map<string, ClawclawPerceptionClass>();
125
+ const modules = new Map<string, ClawclawPerception>();
126
+ const startupFailures: Array<Readonly<Record<string, unknown>>> = [];
127
+
128
+ for (const spec of data.modules) {
129
+ try {
130
+ if (
131
+ !spec
132
+ || typeof spec.moduleId !== 'string'
133
+ || !spec.moduleId
134
+ || typeof spec.sourceUrl !== 'string'
135
+ || !spec.sourceUrl
136
+ || specs.has(spec.moduleId)
137
+ ) throw new Error('perception_reducer_worker_module_invalid');
138
+ const ModuleClass = validateClass(
139
+ spec,
140
+ await import(spec.sourceUrl) as Record<string, unknown>,
141
+ );
142
+ const instance = new ModuleClass();
143
+ validateInstance(spec, instance);
144
+ specs.set(spec.moduleId, spec);
145
+ classes.set(spec.moduleId, ModuleClass);
146
+ modules.set(spec.moduleId, instance);
147
+ } catch (error) {
148
+ startupFailures.push({
149
+ moduleId: typeof spec?.moduleId === 'string' ? spec.moduleId : '',
150
+ code: errorCode(error),
151
+ messagePresent: errorMessage(error).length > 0,
152
+ messageLength: errorMessage(error).length,
153
+ });
154
+ }
155
+ }
156
+
157
+ function safeDebugSnapshot(module: ClawclawPerception): unknown {
158
+ try {
159
+ const snapshot = structuredClone(module.debugSnapshot?.() ?? null);
160
+ assertRuntimeModuleOutputSize(snapshot, 'perception_debug_snapshot');
161
+ return snapshot;
162
+ } catch {
163
+ return null;
164
+ }
165
+ }
166
+
167
+ async function operate(request: PerceptionReducerRequest): Promise<void> {
168
+ if (
169
+ request.poolId !== data!.poolId
170
+ || typeof request.requestId !== 'string'
171
+ || !request.requestId
172
+ || typeof request.moduleId !== 'string'
173
+ || !['update', 'commit', 'flush', 'reset'].includes(request.operation)
174
+ ) throw new Error('perception_reducer_worker_request_invalid');
175
+ const spec = specs.get(request.moduleId);
176
+ const ModuleClass = classes.get(request.moduleId);
177
+ const module = modules.get(request.moduleId);
178
+ if (!spec || !ModuleClass || !module) throw new Error('perception_reducer_worker_module_unknown');
179
+
180
+ try {
181
+ let value;
182
+ if (request.operation === 'update') {
183
+ if ((spec.manifest.execution ?? 'ordered_update') !== 'ordered_update' || !request.frame) {
184
+ throw new Error('perception_reducer_update_invalid');
185
+ }
186
+ value = await module.update(deepFreeze(request.frame), api);
187
+ } else if (request.operation === 'commit') {
188
+ if (spec.manifest.execution !== 'parallel_analysis' || !request.frame) {
189
+ throw new Error('perception_reducer_commit_invalid');
190
+ }
191
+ value = await (module as ClawclawPerception & {
192
+ commit(
193
+ frame: Readonly<PerceptionFrame>,
194
+ analysis: unknown,
195
+ capability: typeof api,
196
+ ): unknown | Promise<unknown>;
197
+ }).commit(
198
+ deepFreeze(request.frame),
199
+ deepFreeze(request.analysis),
200
+ api,
201
+ );
202
+ } else if (request.operation === 'flush') {
203
+ if (!request.boundary) throw new Error('perception_reducer_flush_invalid');
204
+ value = await module.flush?.(deepFreeze(request.boundary), api);
205
+ } else {
206
+ if (typeof request.reason !== 'string') throw new Error('perception_reducer_reset_invalid');
207
+ await module.reset?.(request.reason);
208
+ }
209
+
210
+ const events = request.operation === 'reset'
211
+ ? []
212
+ : normalizePerceptionEvents(
213
+ value as Parameters<typeof normalizePerceptionEvents>[0],
214
+ spec.manifest,
215
+ );
216
+ send({
217
+ type: 'result',
218
+ requestId: request.requestId,
219
+ moduleId: request.moduleId,
220
+ events,
221
+ debugSnapshot: safeDebugSnapshot(module),
222
+ });
223
+ } catch (error) {
224
+ // commit/reset may have partially mutated private reducer state. Match the
225
+ // direct runner contract by replacing that instance before the next frame.
226
+ if (request.operation === 'commit' || request.operation === 'reset') {
227
+ const replacement = new ModuleClass();
228
+ validateInstance(spec, replacement);
229
+ modules.set(request.moduleId, replacement);
230
+ }
231
+ send({
232
+ type: 'request_error',
233
+ requestId: request.requestId,
234
+ moduleId: request.moduleId,
235
+ code: errorCode(error),
236
+ messagePresent: errorMessage(error).length > 0,
237
+ messageLength: errorMessage(error).length,
238
+ debugSnapshot: safeDebugSnapshot(modules.get(request.moduleId)!),
239
+ });
240
+ }
241
+ }
242
+
243
+ let operationTail = Promise.resolve();
244
+ port.on('message', (request: PerceptionReducerRequest) => {
245
+ operationTail = operationTail.then(() => operate(request)).catch((error) => {
246
+ send({
247
+ type: 'error',
248
+ requestId: typeof request?.requestId === 'string' ? request.requestId : undefined,
249
+ moduleId: typeof request?.moduleId === 'string' ? request.moduleId : undefined,
250
+ code: errorCode(error),
251
+ });
252
+ });
253
+ });
254
+
255
+ send({
256
+ type: 'ready',
257
+ moduleIds: [...modules.keys()],
258
+ startupFailures,
259
+ debugSnapshots: Object.fromEntries(
260
+ [...modules].map(([moduleId, module]) => [moduleId, safeDebugSnapshot(module)]),
261
+ ),
262
+ });
@@ -9,7 +9,11 @@ import {
9
9
  type ClawclawTriggerManifest,
10
10
  } from '../../../../sdk/trigger-plugin/index.js';
11
11
  import { normalizeBehaviorInput, normalizeBehaviorInputFields } from '../../behavior-input-fields.js';
12
- import { importRuntimeModule } from '../../../framework/modules/runtime-module-loader.js';
12
+ import {
13
+ importRuntimeModule,
14
+ runtimeModuleThreadLoaderConfig,
15
+ type RuntimeModuleThreadLoaderConfig,
16
+ } from '../../../framework/modules/runtime-module-loader.js';
13
17
  import { assertPluginApiVersion } from '../plugin-api-version.js';
14
18
  import type { ResolvedClawclawTriggerSource } from './trigger-source.js';
15
19
 
@@ -74,11 +78,45 @@ function normalizedManifest(value: unknown): ClawclawTriggerManifest {
74
78
  return structuredClone({ ...manifest, inputs }) as unknown as ClawclawTriggerManifest;
75
79
  }
76
80
 
81
+ export interface TriggerThreadModuleSpec {
82
+ readonly triggerId: string;
83
+ readonly sourceUrl: string;
84
+ readonly source: ResolvedClawclawTriggerSource;
85
+ }
86
+
87
+ export function validateClawclawTriggerModule(
88
+ loaded: Readonly<Record<string, unknown>>,
89
+ source: ResolvedClawclawTriggerSource,
90
+ ): ClawclawTriggerClass {
91
+ if (typeof loaded.default !== 'function') {
92
+ throw new Error(`Trigger module '${source.id}' has no default class.`);
93
+ }
94
+ const ModuleClass = loaded.default as unknown as ClawclawTriggerClass;
95
+ const manifest = normalizedManifest(ModuleClass.manifest);
96
+ if (!isDeepStrictEqual(manifest, source.manifest)) {
97
+ throw new Error(`Trigger module '${source.id}' changed after static discovery.`);
98
+ }
99
+ return ModuleClass;
100
+ }
101
+
77
102
  /** One Runtime-scoped direct importer. Disabled Trigger sources never reach it. */
78
103
  export class TriggerModuleLoader {
79
104
  private readonly runtimeId = randomUUID();
80
105
  private readonly loaded = new Map<string, Promise<ClawclawTriggerClass>>();
81
106
 
107
+ threadConfig(): RuntimeModuleThreadLoaderConfig {
108
+ return runtimeModuleThreadLoaderConfig();
109
+ }
110
+
111
+ threadSpec(source: ResolvedClawclawTriggerSource): TriggerThreadModuleSpec {
112
+ assertPluginApiVersion(
113
+ 'trigger_api_version_unsupported',
114
+ TRIGGER_PLUGIN_API_VERSION,
115
+ source.apiVersion,
116
+ );
117
+ return { triggerId: source.id, sourceUrl: this.sourceUrl(source), source };
118
+ }
119
+
82
120
  load(source: ResolvedClawclawTriggerSource): Promise<ClawclawTriggerClass> {
83
121
  try {
84
122
  assertPluginApiVersion(
@@ -91,17 +129,8 @@ export class TriggerModuleLoader {
91
129
  }
92
130
  let pending = this.loaded.get(source.id);
93
131
  if (pending) return pending;
94
- pending = importRuntimeModule(new URL(this.sourceUrl(source))).then((loaded) => {
95
- if (typeof loaded.default !== 'function') {
96
- throw new Error(`Trigger module '${source.id}' has no default class.`);
97
- }
98
- const ModuleClass = loaded.default as unknown as ClawclawTriggerClass;
99
- const manifest = normalizedManifest(ModuleClass.manifest);
100
- if (!isDeepStrictEqual(manifest, source.manifest)) {
101
- throw new Error(`Trigger module '${source.id}' changed after static discovery.`);
102
- }
103
- return ModuleClass;
104
- });
132
+ pending = importRuntimeModule(new URL(this.sourceUrl(source)))
133
+ .then((loaded) => validateClawclawTriggerModule(loaded, source));
105
134
  this.loaded.set(source.id, pending);
106
135
  return pending;
107
136
  }