@myclaw163/clawclaw-cli 0.9.0 → 0.9.2

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 (86) hide show
  1. package/README.md +5 -3
  2. package/docs/custom-modules/README.md +19 -24
  3. package/docs/custom-modules/api-reference.md +85 -33
  4. package/docs/custom-modules/behavior.md +116 -22
  5. package/docs/custom-modules/examples/auto-escape.ts +41 -0
  6. package/docs/custom-modules/examples/first-sighting-v3.ts +29 -0
  7. package/docs/custom-modules/examples/nearby-reflex.ts +22 -0
  8. package/docs/custom-modules/perception.md +158 -276
  9. package/docs/custom-modules/trigger.md +5 -3
  10. package/docs/runtime/README.md +17 -8
  11. package/docs/runtime/agent-notifications.md +32 -15
  12. package/docs/runtime/behavior-runtime.md +36 -24
  13. package/docs/runtime/components-and-boundaries.md +56 -108
  14. package/docs/runtime/events-and-state.md +55 -3
  15. package/docs/runtime/owner-lifecycle-and-observability.md +5 -3
  16. package/docs/user-guide/README.md +6 -6
  17. package/docs/user-guide/api-reference.md +80 -30
  18. package/docs/user-guide/behavior.md +116 -22
  19. package/docs/user-guide/perception.md +157 -275
  20. package/package.json +1 -1
  21. package/scripts/check-skill-command-surface.mjs +2 -2
  22. package/skills/clawclaw/SKILL.md +9 -7
  23. package/skills/clawclaw/references/BEHAVIORS.md +19 -6
  24. package/skills/clawclaw/references/COMMANDS.md +19 -0
  25. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +116 -22
  26. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +82 -35
  27. package/skills/clawclaw/references/CUSTOM-MODULES.md +18 -23
  28. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +158 -276
  29. package/skills/clawclaw/references/STREAM.md +1 -1
  30. package/src/commands/behavior.ts +28 -99
  31. package/src/commands/load.ts +23 -29
  32. package/src/commands/module-runtime-control.ts +113 -0
  33. package/src/commands/perception.ts +20 -6
  34. package/src/commands/trigger.ts +1 -1
  35. package/src/lib/agent-workspace-sync.ts +2 -2
  36. package/src/runtime/clawclaw/behavior-read-api.ts +4 -0
  37. package/src/runtime/clawclaw/behavior-reflex-control.ts +74 -0
  38. package/src/runtime/clawclaw/owner.ts +51 -5
  39. package/src/runtime/clawclaw/perception-module-manifest.ts +36 -0
  40. package/src/runtime/clawclaw/plugins/assembly.ts +25 -23
  41. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +16 -3
  42. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +4 -0
  43. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +2 -0
  44. package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +3 -0
  45. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +129 -57
  46. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +7 -2
  47. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -1
  48. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +21 -18
  49. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +3 -2
  50. package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +2 -0
  51. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +84 -0
  52. package/src/runtime/clawclaw/plugins/{source → derived-event}/task-change-tracker.ts +1 -1
  53. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +314 -0
  54. package/src/runtime/clawclaw/plugins/perception/{reaction-runner.ts → perception-module-runner.ts} +26 -13
  55. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +39 -0
  56. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +1 -1
  57. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +30 -7
  58. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +2 -103
  59. package/src/runtime/clawclaw/plugins/trigger/contracts.ts +3 -1
  60. package/src/runtime/clawclaw/plugins/trigger/trigger-module-loader.ts +5 -2
  61. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +61 -10
  62. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-pool.ts +13 -1
  63. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-worker.ts +4 -0
  64. package/src/runtime/clawclaw/reaction-manifest.ts +18 -12
  65. package/src/runtime/clawclaw/runtime-state.ts +1 -1
  66. package/src/runtime/clawclaw/runtime.ts +3 -3
  67. package/src/runtime/clawclaw/strategy-memory-rpc.ts +63 -0
  68. package/src/runtime/clawclaw/strategy-memory.ts +77 -0
  69. package/src/runtime/clawclaw-event-catalog.ts +9 -6
  70. package/src/runtime/framework/plugins/contracts.ts +8 -0
  71. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +17 -6
  72. package/src/runtime/owner-control.ts +5 -0
  73. package/src/sdk/behavior-plugin/index.ts +4 -1
  74. package/src/sdk/index.ts +5 -0
  75. package/src/sdk/perception-plugin/index.ts +29 -10
  76. package/src/sdk/perception-plugin/module.ts +55 -0
  77. package/src/sdk/perception-plugin/reaction.ts +2 -1
  78. package/src/sdk/perception-plugin/reminder.ts +1 -0
  79. package/src/sdk/strategy-memory.ts +12 -0
  80. package/src/sdk/trigger-plugin/index.ts +3 -2
  81. package/docs/custom-modules/examples/nearby-escape.ts +0 -56
  82. package/docs/custom-modules/examples/nearby-notice.ts +0 -36
  83. package/src/runtime/clawclaw/behavior-activation-capability.ts +0 -21
  84. package/src/runtime/clawclaw/plugins/perception/reaction-plugin.ts +0 -198
  85. package/src/runtime/clawclaw/plugins/perception/reaction-worker.ts +0 -26
  86. /package/src/runtime/clawclaw/plugins/{source → derived-event}/player-change-tracker.ts +0 -0
@@ -1,198 +0,0 @@
1
- import type { RuntimeEpochPlugin, RuntimeEpochPluginContext, RuntimeEpochPluginInput, RuntimeEpochPluginResult,
2
- RuntimeEventProposal } from '../../../framework/plugins/index.js';
3
- import type { ReactionActivation, ReactionInput, ReactionResult } from '../../../../sdk/perception-plugin/reaction.js';
4
- import { normalizeReactionManifest } from '../../reaction-manifest.js';
5
- import { resolveReactionBehavior, type ReactionBehaviorCandidate } from '../../reaction-behavior-resolution.js';
6
- import { BEHAVIOR_ACTIVATION_CAPABILITY, type PerceptionBehaviorActivation,
7
- type PerceptionBehaviorActivationResult } from '../../behavior-activation-capability.js';
8
- import { ObservationFrameProjector } from '../../observation-frame-projector.js';
9
- import { freshClawclawGameState, isClawclawRuntimeState } from '../../runtime-state.js';
10
- import { createCanonicalGameState } from '../../behavior-input.js';
11
- import { projectTaskChoiceEventPayload } from '../../task-choice-projection.js';
12
- import type { ResolvedClawclawPerceptionSource } from './perception-source.js';
13
- import { ReactionRunner } from './reaction-runner.js';
14
- import { resolveClawclawResourceMetadata } from '../../../../sdk/resource-metadata.js';
15
-
16
- export const CLAWCLAW_REACTION_PLUGIN_ID = 'clawclaw.perception.reactions';
17
- export const REACTION_HOST_EVENT_TYPES = ['perception.behavior_unavailable', 'perception.reaction_failed'] as const;
18
- interface BindingState { armed: boolean; lastAcceptedAt?: number; warning?: string; warningSequence: number; failedAttempt?: string }
19
- interface ModuleState { value?: unknown; bindings: Record<string, BindingState> }
20
- interface Checkpoint { gameId?: string; phase?: string; modules: Record<string, ModuleState>; failures: string[] }
21
- export interface ReactionPluginOptions {
22
- sources: readonly ResolvedClawclawPerceptionSource[];
23
- after: readonly string[];
24
- behaviors: () => readonly ReactionBehaviorCandidate[];
25
- runnerFactory?: (source: ResolvedClawclawPerceptionSource) => Pick<ReactionRunner, 'start' | 'evaluate' | 'stop'>;
26
- }
27
- const record = (value: unknown): value is Record<string, any> => !!value && typeof value === 'object' && !Array.isArray(value);
28
-
29
- /** All modules observe their subscribed facts independently. Only own outputs are produced. */
30
- export class ClawclawReactionPlugin implements RuntimeEpochPlugin<Record<string, any>> {
31
- readonly kind = 'epoch' as const;
32
- readonly id = CLAWCLAW_REACTION_PLUGIN_ID;
33
- readonly version = '1';
34
- readonly catchUp = 'strict_ordered' as const;
35
- readonly timeoutMs = 10_000;
36
- readonly after: readonly string[];
37
- readonly consumes: { events: readonly string[] };
38
- readonly produces: { events: readonly string[] };
39
- readonly capabilities = { uses: [BEHAVIOR_ACTIVATION_CAPABILITY] };
40
- private readonly sources: readonly ResolvedClawclawPerceptionSource[];
41
- private readonly runners = new Map<string, Pick<ReactionRunner, 'start' | 'evaluate' | 'stop'>>();
42
- private readonly failed = new Set<string>();
43
- private checkpoint: Checkpoint = { modules: {}, failures: [] };
44
- private readonly projector = new ObservationFrameProjector();
45
- constructor(private readonly options: ReactionPluginOptions) {
46
- this.sources = options.sources.filter(source => source.reaction).map(source => ({
47
- ...source, reaction: normalizeReactionManifest(source.reaction),
48
- })).sort((a, b) => a.id.localeCompare(b.id));
49
- this.after = options.after;
50
- this.consumes = { events: [...new Set(this.sources.flatMap(source => [...source.reaction!.consumes]))] };
51
- this.produces = { events: [...new Set([...REACTION_HOST_EVENT_TYPES,
52
- ...this.sources.flatMap(source => [...source.reaction!.produces])])] };
53
- }
54
- async start(context: RuntimeEpochPluginContext<Record<string, any>>): Promise<void> {
55
- this.checkpoint = { modules: {}, failures: [] }; this.failed.clear(); this.projector.reset();
56
- await Promise.all(this.sources.map(async (source, index) => {
57
- try {
58
- if (index >= 32) throw new Error('REACTION_MODULE_LIMIT');
59
- const runner = this.options.runnerFactory?.(source) ?? new ReactionRunner(source);
60
- this.runners.set(source.id, runner); await runner.start();
61
- } catch {
62
- this.failed.add(source.id); await this.runners.get(source.id)?.stop();
63
- context.diagnostic('reaction.module_failed', { module_id: source.id }, 'warn');
64
- }
65
- }));
66
- }
67
- recover(context: RuntimeEpochPluginContext<Record<string, any>>): void {
68
- const saved = context.checkpoint() as Checkpoint | undefined;
69
- if (saved?.modules && Array.isArray(saved.failures)) this.checkpoint = structuredClone(saved);
70
- this.projector.reset();
71
- }
72
- async stop(): Promise<void> { await Promise.all([...this.runners.values()].map(runner => runner.stop())); this.runners.clear(); }
73
- localizedModuleDescriptors(locale: string) {
74
- return this.sources.filter(source => !this.failed.has(source.id)).map(source =>
75
- resolveClawclawResourceMetadata({ ...source.manifest, display: source.display }, locale));
76
- }
77
- async update(input: RuntimeEpochPluginInput<Record<string, any>>, context: RuntimeEpochPluginContext<Record<string, any>>): Promise<RuntimeEpochPluginResult> {
78
- const raw = freshClawclawGameState(input.frame.state) ?? input.currentState.state;
79
- const connected = !isClawclawRuntimeState(input.frame.state) || input.frame.state.connection === 'connected';
80
- const game = connected && raw?.game_id ? createCanonicalGameState(raw, input.frame.backendTick) : null;
81
- if (game && this.checkpoint.gameId !== game.game_id) this.checkpoint = { gameId: game.game_id, modules: {}, failures: [] };
82
- if (!game || this.checkpoint.phase !== game.phase) {
83
- for (const state of Object.values(this.checkpoint.modules)) {
84
- state.value = undefined;
85
- for (const binding of Object.values(state.bindings)) {
86
- binding.armed = true; binding.lastAcceptedAt = undefined; binding.failedAttempt = undefined;
87
- }
88
- }
89
- this.checkpoint.phase = game?.phase;
90
- }
91
- const frame = this.projector.project(input.frame);
92
- const nowMs = input.frame.observedAtMs ?? input.frame.receivedAtMs;
93
- const candidates = this.options.behaviors();
94
- const facts = input.pendingEvents.filter(event => !event.replayed).map(event => ({
95
- eventId: event.eventId, type: event.type, occurredAt: event.occurredAt, receivedAt: event.receivedAt,
96
- payload: projectTaskChoiceEventPayload(raw, event.type, event.payload), wakeAgent: event.wakeAgent, replayed: false,
97
- }));
98
- const events: RuntimeEventProposal[] = [];
99
- const requests: Array<{ source: ResolvedClawclawPerceptionSource; activation: ReactionActivation; state: BindingState }> = [];
100
- for (const source of this.sources) {
101
- if (!this.failed.has(source.id)) {
102
- try {
103
- const state = Object.hasOwn(this.checkpoint.modules, source.id)
104
- ? this.checkpoint.modules[source.id] : (this.checkpoint.modules[source.id] = { bindings: {} });
105
- const moduleInput: ReactionInput = { moduleId: source.id, scope: input.epoch.scope, gameState: game, frame,
106
- events: facts.filter(event => source.reaction!.consumes.includes(event.type)), nowMs,
107
- state: state.value, config: source.reaction!.config ?? {}, availableBehaviors: candidates.filter(c => c.loadable).map(c => c.id) };
108
- // A control-only epoch is not an observation that clears a visual condition.
109
- if (!frame && moduleInput.events.length === 0) continue;
110
- const result = await this.runners.get(source.id)!.evaluate(moduleInput);
111
- this.validate(result, source);
112
- state.value = structuredClone(result.state);
113
- for (const event of result.events ?? []) events.push({ type: event.type,
114
- dedupeKey: JSON.stringify([source.id, event.key]), dedupeScope: 'segment', wakeAgent: event.wakeAgent ?? true,
115
- payload: { ...event.payload }, occurredAt: new Date(nowMs).toISOString() });
116
- const matched = new Map((result.activations ?? []).map(activation => [activation.behavior, activation]));
117
- for (const [key, binding] of Object.entries(source.reaction!.behaviors ?? {})) {
118
- const current = state.bindings[key] ??= { armed: true, warningSequence: 0 };
119
- if (current.warning === 'behavior_not_loaded' && resolveReactionBehavior(binding, candidates)) current.warning = undefined;
120
- if (!matched.has(key)) { current.armed = true; current.failedAttempt = undefined; continue; }
121
- if (!game || game.phase !== 'wandering' || game.you?.is_alive !== true || !connected) continue;
122
- if ((binding.rearm ?? 'after_clear') === 'after_clear' && !current.armed) continue;
123
- if (current.lastAcceptedAt !== undefined && nowMs - current.lastAcceptedAt < (binding.cooldownMs ?? 1_000)) continue;
124
- requests.push({ source, activation: matched.get(key)!, state: current });
125
- }
126
- } catch {
127
- this.failed.add(source.id); await this.runners.get(source.id)?.stop();
128
- context.diagnostic('reaction.module_failed', { module_id: source.id }, 'warn');
129
- }
130
- }
131
- if (this.failed.has(source.id) && !this.checkpoint.failures.includes(source.id)) {
132
- this.checkpoint.failures.push(source.id);
133
- events.push({ type: 'perception.reaction_failed', wakeAgent: true, dedupeKey: `module:${source.id}`,
134
- payload: { module_id: source.id, text: `感知“${source.name}”的反应脚本不可用,已停止该模块;其他感知和策略继续运行。` } });
135
- }
136
- }
137
- requests.sort((a, b) => (b.source.reaction!.behaviors![b.activation.behavior].reflexPriority ?? 0)
138
- - (a.source.reaction!.behaviors![a.activation.behavior].reflexPriority ?? 0));
139
- for (const { source, activation, state } of requests) {
140
- if (context.signal.aborted) break;
141
- const binding = source.reaction!.behaviors![activation.behavior];
142
- const behavior = resolveReactionBehavior(binding, this.options.behaviors());
143
- const attempt = JSON.stringify([behavior, binding.input ?? {}, activation.input ?? {}]);
144
- if (state.failedAttempt === attempt) continue;
145
- let result: PerceptionBehaviorActivationResult = { accepted: false, reason: 'behavior_not_loaded' };
146
- if (behavior) {
147
- try {
148
- const response = await context.capabilities.performAction<PerceptionBehaviorActivation, PerceptionBehaviorActivationResult>(
149
- BEHAVIOR_ACTIVATION_CAPABILITY, { moduleId: source.id, bindingKey: activation.behavior, behavior,
150
- input: { ...binding.input, ...activation.input }, layer: binding.layer ?? 'reflex',
151
- reflexPriority: binding.reflexPriority ?? 0,
152
- maxRuntimeMs: binding.maxRuntimeMs ?? ((binding.layer ?? 'reflex') === 'long' ? undefined : 10_000),
153
- epochId: input.epoch.epochSeq, gameId: game!.game_id,
154
- reason: activation.reason ?? `perception:${source.id}:${activation.behavior}` });
155
- result = response.value ?? { accepted: false, reason: 'activation_unavailable' };
156
- } catch { result = { accepted: false, reason: 'activation_unavailable' }; }
157
- }
158
- if (result.accepted) {
159
- state.armed = false; state.lastAcceptedAt = nowMs; state.warning = undefined; state.failedAttempt = undefined;
160
- } else if (!['same_trigger_active', 'reflex_priority_not_higher', 'stale_request', 'activation_ineligible'].includes(result.reason ?? '')) {
161
- const reason = result.reason ?? 'activation_unavailable';
162
- state.failedAttempt = attempt;
163
- if (state.warning !== reason) {
164
- state.warning = reason; state.warningSequence++;
165
- events.push({ type: 'perception.behavior_unavailable', wakeAgent: true,
166
- dedupeKey: JSON.stringify([game?.game_id, source.id, activation.behavior, state.warningSequence]),
167
- payload: { module_id: source.id, binding: activation.behavior, behavior_name: binding.name,
168
- ...(binding.resourceId ? { preferred_resource_id: binding.resourceId } : {}),
169
- ...(behavior ? { behavior_id: behavior } : {}), reason,
170
- text: `感知“${source.name}”未能触发策略“${binding.name}”(${reason})。已跳过本次触发,请 Agent 判断处理;其他感知和策略继续运行。` } });
171
- }
172
- }
173
- }
174
- return { outcome: 'processed', events, checkpoint: structuredClone(this.checkpoint),
175
- ...(input.pendingEvents.length ? { consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq } : {}) };
176
- }
177
- private validate(result: ReactionResult, source: ResolvedClawclawPerceptionSource): void {
178
- if (!record(result) || Object.keys(result).some(key => !['state', 'events', 'activations'].includes(key))
179
- || result.events !== undefined && !Array.isArray(result.events)
180
- || result.activations !== undefined && !Array.isArray(result.activations)
181
- || (result.events?.length ?? 0) > 32 || (result.activations?.length ?? 0) > 16
182
- || Buffer.byteLength(JSON.stringify(result)) > 128_000) throw new Error('REACTION_OUTPUT_INVALID');
183
- for (const event of result.events ?? []) {
184
- if (!record(event) || !source.reaction!.produces.includes(event.type)
185
- || typeof event.key !== 'string' || !event.key.trim() || event.key.length > 512
186
- || event.wakeAgent !== undefined && typeof event.wakeAgent !== 'boolean'
187
- || !record(event.payload) || typeof event.payload.text !== 'string' || !event.payload.text.trim()) throw new Error('REACTION_EVENT_INVALID');
188
- }
189
- const bindings = new Set<string>();
190
- for (const activation of result.activations ?? []) {
191
- if (!record(activation) || !Object.hasOwn(source.reaction!.behaviors ?? {}, activation.behavior)
192
- || bindings.has(activation.behavior) || activation.input !== undefined && !record(activation.input)
193
- || activation.reason !== undefined && (typeof activation.reason !== 'string' || activation.reason.length > 512)
194
- || Object.keys(activation).some(key => !['behavior', 'input', 'reason'].includes(key))) throw new Error('REACTION_ACTIVATION_INVALID');
195
- bindings.add(activation.behavior);
196
- }
197
- }
198
- }
@@ -1,26 +0,0 @@
1
- import { parentPort, workerData } from 'node:worker_threads';
2
- import { pathToFileURL } from 'node:url';
3
- import { ClawclawReaction, type ReactionInput } from '../../../../sdk/perception-plugin/reaction.js';
4
- import { normalizeReactionManifest } from '../../reaction-manifest.js';
5
-
6
- function freeze<T>(value: T): T {
7
- if (value && typeof value === 'object' && !Object.isFrozen(value)) {
8
- for (const child of Object.values(value)) freeze(child); Object.freeze(value);
9
- }
10
- return value;
11
- }
12
- try {
13
- const Module = (await import(pathToFileURL(workerData.modulePath).href)).default;
14
- if (!(Module?.prototype instanceof ClawclawReaction)) throw new Error('REACTION_CLASS_INVALID');
15
- const manifest = normalizeReactionManifest(Module.manifest);
16
- if (JSON.stringify(manifest) !== JSON.stringify(workerData.expectedManifest)) throw new Error('REACTION_MANIFEST_CHANGED');
17
- parentPort!.postMessage({ type: 'ready' });
18
- parentPort!.on('message', async ({ id, input }: { id: number; input: ReactionInput }) => {
19
- try {
20
- const result = await new Module().evaluate(freeze({ ...input, config: manifest.config ?? {},
21
- events: input.events.filter(e => manifest.consumes.includes(e.type)) }));
22
- if (Buffer.byteLength(JSON.stringify(result) ?? '') > 128_000) throw new Error('REACTION_OUTPUT_TOO_LARGE');
23
- parentPort!.postMessage({ type: 'result', id, result });
24
- } catch { parentPort!.postMessage({ type: 'error', id }); }
25
- });
26
- } catch { parentPort!.postMessage({ type: 'error' }); }