@myclaw163/clawclaw-cli 0.8.38 → 0.8.39
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.
- package/docs/custom-modules/README.md +6 -4
- package/docs/custom-modules/api-reference.md +10 -0
- package/docs/custom-modules/examples/nearby-escape.ts +49 -0
- package/docs/custom-modules/perception.md +114 -5
- package/docs/custom-modules/trigger.md +2 -0
- package/docs/runtime/components-and-boundaries.md +2 -2
- package/package.json +1 -1
- package/skills/clawclaw/SKILL.md +10 -4
- package/skills/clawclaw/references/BEHAVIORS.md +6 -2
- package/skills/clawclaw/references/CUSTOM-MODULE-API.md +13 -0
- package/skills/clawclaw/references/CUSTOM-MODULES.md +3 -1
- package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +114 -5
- package/src/commands/load.ts +25 -1
- package/src/commands/perception.ts +1 -0
- package/src/lib/agent-workspace-runtime.ts +11 -5
- package/src/lib/capability-load-diagnostics.ts +1 -1
- package/src/lib/capability-operation-name.ts +1 -0
- package/src/runtime/clawclaw/behavior-activation-capability.ts +21 -0
- package/src/runtime/clawclaw/owner.ts +8 -3
- package/src/runtime/clawclaw/plugins/assembly.ts +20 -3
- package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -1
- package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +4 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +72 -9
- package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +2 -0
- package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +1 -1
- package/src/runtime/clawclaw/plugins/perception/perception-source.ts +14 -1
- package/src/runtime/clawclaw/plugins/perception/reaction-plugin.ts +198 -0
- package/src/runtime/clawclaw/plugins/perception/reaction-runner.ts +49 -0
- package/src/runtime/clawclaw/plugins/perception/reaction-worker.ts +26 -0
- package/src/runtime/clawclaw/reaction-behavior-resolution.ts +23 -0
- package/src/runtime/clawclaw/reaction-manifest.ts +50 -0
- package/src/runtime/clawclaw/runtime.ts +3 -0
- package/src/runtime/clawclaw-event-catalog.ts +5 -1
- package/src/sdk/perception-plugin/index.ts +1 -0
- package/src/sdk/perception-plugin/reaction.ts +78 -0
package/src/commands/load.ts
CHANGED
|
@@ -29,6 +29,7 @@ import {
|
|
|
29
29
|
import { BEHAVIOR_PLUGIN_API_VERSION } from '../sdk/behavior-plugin/index.js';
|
|
30
30
|
import { TRIGGER_PLUGIN_API_VERSION } from '../sdk/trigger-plugin/index.js';
|
|
31
31
|
import { PERCEPTION_PLUGIN_API_VERSION } from '../sdk/perception-plugin/index.js';
|
|
32
|
+
import { resolveReactionBehavior } from '../runtime/clawclaw/reaction-behavior-resolution.js';
|
|
32
33
|
import { pluginApiVersionStatus } from '../runtime/clawclaw/plugins/plugin-api-version.js';
|
|
33
34
|
import {
|
|
34
35
|
readLocalAgentWorkspaceSnapshot,
|
|
@@ -421,6 +422,7 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
|
|
|
421
422
|
const enabledBehaviors = mergeAgentWorkspaceBehaviorSources(
|
|
422
423
|
localBehaviors,
|
|
423
424
|
hubBehaviors,
|
|
425
|
+
disabledBehaviors,
|
|
424
426
|
);
|
|
425
427
|
const behaviorEntry = (source: typeof enabledBehaviors[number]) => {
|
|
426
428
|
const compatibilityError = behaviorSourceCompatibilityError(source);
|
|
@@ -596,6 +598,7 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
|
|
|
596
598
|
const enabledPerceptions = mergeAgentWorkspacePerceptionSources(
|
|
597
599
|
localPerceptions,
|
|
598
600
|
hubPerceptions,
|
|
601
|
+
disabledPerceptions,
|
|
599
602
|
);
|
|
600
603
|
const reminderTopics = new Map<string, string[]>();
|
|
601
604
|
for (const source of enabledPerceptions) {
|
|
@@ -619,6 +622,24 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
|
|
|
619
622
|
const perceptions = enabledPerceptions
|
|
620
623
|
.filter(({ apiVersion, id }) => apiVersion === PERCEPTION_PLUGIN_API_VERSION && !conflictingPerceptions.has(id))
|
|
621
624
|
.map(perceptionEntry);
|
|
625
|
+
const behaviorDependencies = new Map<string, Array<Record<string, unknown>>>();
|
|
626
|
+
const availableBehaviorIdsForReactions = new Set(behaviors.map(entry => entry.id));
|
|
627
|
+
const reactionCandidates = enabledBehaviors.map(source => ({ id: source.id, declaredId: source.declaredId,
|
|
628
|
+
resourceId: source.resourceId, loadable: availableBehaviorIdsForReactions.has(source.id) }));
|
|
629
|
+
for (const source of enabledPerceptions.filter(source => source.reaction && source.apiVersion === PERCEPTION_PLUGIN_API_VERSION)) {
|
|
630
|
+
const bindings = Object.entries(source.reaction!.behaviors ?? {}).map(([key, binding]) => {
|
|
631
|
+
const resolved = resolveReactionBehavior(binding, reactionCandidates);
|
|
632
|
+
if (!resolved) configurationWarnings.push({ code: 'PERCEPTION_BEHAVIOR_UNAVAILABLE',
|
|
633
|
+
perception_id: source.id, binding: key, behavior_name: binding.name,
|
|
634
|
+
...(binding.resourceId ? { preferred_resource_id: binding.resourceId } : {}),
|
|
635
|
+
reason: 'no_loaded_matching_behavior',
|
|
636
|
+
message: `Perception ${source.id} cannot activate ${binding.name}: no matching Behavior is loaded. Only this reaction is unavailable; other perception output and CCL continue. Equip a matching Behavior and run ccl load again; changes take effect in the next Runtime.` });
|
|
637
|
+
return { binding: key, name: binding.name, layer: binding.layer ?? 'reflex', available: !!resolved,
|
|
638
|
+
...(binding.resourceId ? { preferred_resource_id: binding.resourceId } : {}),
|
|
639
|
+
...(resolved ? { behavior_id: resolved } : {}) };
|
|
640
|
+
});
|
|
641
|
+
behaviorDependencies.set(source.id, bindings);
|
|
642
|
+
}
|
|
622
643
|
const incompatiblePerceptions = enabledPerceptions
|
|
623
644
|
.filter(({ apiVersion }) => apiVersion !== PERCEPTION_PLUGIN_API_VERSION)
|
|
624
645
|
.map(perceptionEntry);
|
|
@@ -647,7 +668,9 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
|
|
|
647
668
|
const disabledTriggers = new Set(gameplay.disabled_triggers);
|
|
648
669
|
const localTriggerDir = getUserDataAccountTriggersDir(workspaceDir, profile);
|
|
649
670
|
const triggerSources = listClawclawTriggerSources(localTriggerDir);
|
|
650
|
-
const enabledTriggers = triggerSources.filter((source) => !disabledTriggers.has(source.id)
|
|
671
|
+
const enabledTriggers = triggerSources.filter((source) => !disabledTriggers.has(source.id)
|
|
672
|
+
&& !enabledPerceptions.some(perception => perception.reaction && perception.apiVersion === PERCEPTION_PLUGIN_API_VERSION
|
|
673
|
+
&& (perception.declaredId ?? perception.id) === source.id));
|
|
651
674
|
const triggerSourcePaths = new Set(triggerSources.map(({ sourcePath }) => resolve(sourcePath)));
|
|
652
675
|
let expectedLocalTriggers = enabledTriggers.length;
|
|
653
676
|
for (const path of listCapabilityModuleCandidates(localTriggerDir)) {
|
|
@@ -943,6 +966,7 @@ export function createLoadCommand(dependencies: LoadCommandDependencies = {}): C
|
|
|
943
966
|
name: localized.name,
|
|
944
967
|
description: source.description,
|
|
945
968
|
source: entry.source,
|
|
969
|
+
...(source.reaction ? { kind: 'reaction', behavior_dependencies: behaviorDependencies.get(source.id) ?? [] } : {}),
|
|
946
970
|
};
|
|
947
971
|
}),
|
|
948
972
|
triggers: triggers.map((entry) => {
|
|
@@ -112,6 +112,7 @@ Perception modules:
|
|
|
112
112
|
runtime_source_path: source.sourcePath,
|
|
113
113
|
name: source.name,
|
|
114
114
|
description: source.description,
|
|
115
|
+
...(source.reaction ? { kind: 'reaction', behaviors: source.reaction.behaviors } : {}),
|
|
115
116
|
source: hubIds.has(source.id) ? 'hub' : 'local',
|
|
116
117
|
...pluginApiVersionStatus(
|
|
117
118
|
'perception',
|
|
@@ -91,6 +91,7 @@ export function listAgentWorkspaceBehaviorSources(
|
|
|
91
91
|
&& item.resolution !== 'local_origin_unrecognized';
|
|
92
92
|
const managed = {
|
|
93
93
|
...source,
|
|
94
|
+
resourceId: item.resourceId,
|
|
94
95
|
...(trusted ? { trustedSourceSha256: item.sourceFiles[0]!.sha256 } : {}),
|
|
95
96
|
management: {
|
|
96
97
|
source: 'hub',
|
|
@@ -168,14 +169,17 @@ export function listAgentWorkspacePerceptionSources(
|
|
|
168
169
|
export function mergeAgentWorkspaceBehaviorSources(
|
|
169
170
|
base: readonly ResolvedClawclawBehaviorSource[],
|
|
170
171
|
cloud: readonly ResolvedClawclawBehaviorSource[],
|
|
172
|
+
disabled?: ReadonlySet<string>,
|
|
171
173
|
): readonly ManagedClawclawBehaviorSource[] {
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
174
|
+
const activeBase = base.filter(source => !disabled?.has(source.id));
|
|
175
|
+
const activeCloud = cloud.filter(source => !disabled?.has(source.id));
|
|
176
|
+
assertUniqueBehaviorIds(activeBase, 'local');
|
|
177
|
+
assertUniqueBehaviorIds(activeCloud, 'hub');
|
|
178
|
+
const merged = new Map<string, ManagedClawclawBehaviorSource>(activeBase.map((source) => [source.id, {
|
|
175
179
|
...source,
|
|
176
180
|
management: { source: 'local', managedBy: 'local_config' },
|
|
177
181
|
} satisfies ManagedClawclawBehaviorSource]));
|
|
178
|
-
for (const source of
|
|
182
|
+
for (const source of activeCloud) {
|
|
179
183
|
if (merged.has(source.id)) continue;
|
|
180
184
|
merged.set(source.id, {
|
|
181
185
|
...source,
|
|
@@ -190,9 +194,11 @@ export function mergeAgentWorkspaceBehaviorSources(
|
|
|
190
194
|
export function mergeAgentWorkspacePerceptionSources(
|
|
191
195
|
base: readonly ResolvedClawclawPerceptionSource[],
|
|
192
196
|
cloud: readonly ResolvedClawclawPerceptionSource[],
|
|
197
|
+
disabled?: ReadonlySet<string>,
|
|
193
198
|
): readonly ResolvedClawclawPerceptionSource[] {
|
|
194
|
-
const merged = new Map(base.map((source) => [source.id, source]));
|
|
199
|
+
const merged = new Map(base.filter(source => !disabled?.has(source.id)).map((source) => [source.id, source]));
|
|
195
200
|
for (const source of cloud) {
|
|
201
|
+
if (disabled?.has(source.id)) continue;
|
|
196
202
|
if (merged.has(source.id)) {
|
|
197
203
|
throw new Error(`AGENT_RESOURCE_ID_CONFLICT:perception:${source.id}`);
|
|
198
204
|
}
|
|
@@ -72,7 +72,7 @@ const MODULE_CONTRACTS: Record<ModuleCapabilityType, {
|
|
|
72
72
|
perception: {
|
|
73
73
|
expectedImport: '@myclaw163/clawclaw-cli/perception-plugin',
|
|
74
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|ClawclawReminder)/,
|
|
75
|
+
defaultClass: /export\s+default\s+class(?:\s+[A-Za-z_$][\w$]*)?\s+extends\s+(?:ClawclawPerception|ClawclawParallelPerception|ClawclawReminder|ClawclawReaction)/,
|
|
76
76
|
manifest: /\bstatic\s+(?:readonly\s+)?manifest\s*=\s*\{/,
|
|
77
77
|
},
|
|
78
78
|
trigger: {
|
|
@@ -4,6 +4,7 @@ import type { ResolvedClawclawPerceptionSource } from '../runtime/clawclaw/plugi
|
|
|
4
4
|
|
|
5
5
|
export function behaviorOperationName<T extends ResolvedClawclawBehaviorSource>(source: T, entry: CapabilityWorkspaceEntry): T {
|
|
6
6
|
return { ...source, id: entry.runtimeId, declaredId: source.declaredId ?? source.id,
|
|
7
|
+
...(entry.hub ? { resourceId: entry.hub.resourceId } : {}),
|
|
7
8
|
display: { name: entry.title, description: entry.description },
|
|
8
9
|
workingCopyPath: source.workingCopyPath ?? source.sourcePath };
|
|
9
10
|
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { ReactionBehaviorBinding } from '../../sdk/perception-plugin/reaction.js';
|
|
2
|
+
|
|
3
|
+
/** Generic module activation port. It is independent of model decision providers. */
|
|
4
|
+
export const BEHAVIOR_ACTIVATION_CAPABILITY = 'clawclaw.behavior.activate';
|
|
5
|
+
export interface PerceptionBehaviorActivation {
|
|
6
|
+
readonly moduleId: string;
|
|
7
|
+
readonly bindingKey: string;
|
|
8
|
+
readonly behavior: string;
|
|
9
|
+
readonly input: Readonly<Record<string, unknown>>;
|
|
10
|
+
readonly layer: NonNullable<ReactionBehaviorBinding['layer']>;
|
|
11
|
+
readonly reflexPriority: number;
|
|
12
|
+
readonly maxRuntimeMs?: number;
|
|
13
|
+
readonly reason: string;
|
|
14
|
+
readonly epochId: number;
|
|
15
|
+
readonly gameId: string;
|
|
16
|
+
}
|
|
17
|
+
export interface PerceptionBehaviorActivationResult {
|
|
18
|
+
readonly accepted: boolean;
|
|
19
|
+
readonly reason?: string;
|
|
20
|
+
readonly activationId?: string;
|
|
21
|
+
}
|
|
@@ -583,6 +583,7 @@ export async function runClawclawOwner(
|
|
|
583
583
|
))
|
|
584
584
|
.map(({ source }) => source),
|
|
585
585
|
agentBehaviorSources,
|
|
586
|
+
disabledBehaviors,
|
|
586
587
|
);
|
|
587
588
|
const behaviorSourceById = new Map(behaviorSources.map((source) => [source.id, source]));
|
|
588
589
|
const behaviorCatalog = new ClawclawBehaviorCatalog(behaviorSources);
|
|
@@ -618,6 +619,7 @@ export async function runClawclawOwner(
|
|
|
618
619
|
const perceptionSources = mergeAgentWorkspacePerceptionSources(
|
|
619
620
|
localPerceptionSources,
|
|
620
621
|
agentPerceptionSources,
|
|
622
|
+
disabledPerceptions,
|
|
621
623
|
);
|
|
622
624
|
const perceptionModules = [
|
|
623
625
|
...localPerceptionSources.map(({ id }) => id),
|
|
@@ -655,6 +657,7 @@ export async function runClawclawOwner(
|
|
|
655
657
|
visualEventDelivery: perceptionConfig.events.delivery,
|
|
656
658
|
visualEventTypes: assembly.perception.produces.events,
|
|
657
659
|
behaviorEventTypes: assembly.behavior.produces?.events ?? [],
|
|
660
|
+
reactionEventTypes: assembly.reactions?.produces.events,
|
|
658
661
|
});
|
|
659
662
|
if (fullDiagnosticsEnabled) {
|
|
660
663
|
processTimingSampler = new RuntimeProcessTimingSampler();
|
|
@@ -783,7 +786,8 @@ export async function runClawclawOwner(
|
|
|
783
786
|
: null;
|
|
784
787
|
})(),
|
|
785
788
|
perceptions: [...assembly.perception.localizedModuleDescriptors(DESKTOP_RESOURCE_LOCALE),
|
|
786
|
-
...assembly.reminders.localizedModuleDescriptors(DESKTOP_RESOURCE_LOCALE)
|
|
789
|
+
...assembly.reminders.localizedModuleDescriptors(DESKTOP_RESOURCE_LOCALE),
|
|
790
|
+
...(assembly.reactions?.localizedModuleDescriptors(DESKTOP_RESOURCE_LOCALE) ?? [])],
|
|
787
791
|
}),
|
|
788
792
|
eventDescriptors: () => assembly.perception
|
|
789
793
|
.localizedEventDescriptors(DESKTOP_RESOURCE_LOCALE)
|
|
@@ -1194,14 +1198,15 @@ export async function runClawclawOwner(
|
|
|
1194
1198
|
return { ok: false, type: 'behavior_fallback', error: 'stale_runtime_scope' };
|
|
1195
1199
|
}
|
|
1196
1200
|
const latest = readGameplayConfig(workspaceDir, options.profile);
|
|
1197
|
-
|
|
1201
|
+
const currentRole = readyRoleForScope(runtime!, expected);
|
|
1202
|
+
if (currentRole === role) {
|
|
1198
1203
|
await assembly.behavior.noteAgentActivity();
|
|
1199
1204
|
}
|
|
1200
1205
|
await assembly.behavior.configureFallbackBehaviors(roleFallbackBehaviors(
|
|
1201
1206
|
latest,
|
|
1202
1207
|
behaviorCatalog,
|
|
1203
1208
|
configurationWarning,
|
|
1204
|
-
));
|
|
1209
|
+
), currentRole);
|
|
1205
1210
|
return {
|
|
1206
1211
|
ok: true,
|
|
1207
1212
|
type: 'behavior_fallback',
|
|
@@ -2,6 +2,7 @@ import type { GameClient } from '../../../lib/game-client.js';
|
|
|
2
2
|
import { ClawclawReminderPlugin, CLAWCLAW_REMINDER_PLUGIN_ID } from './derived-event/reminder-plugin.js';
|
|
3
3
|
import { listClawclawPerceptionSources } from './perception/perception-source.js';
|
|
4
4
|
import { DEFAULT_PERCEPTION_MODULES } from './perception/official-module-ids.js';
|
|
5
|
+
import { ClawclawReactionPlugin, CLAWCLAW_REACTION_PLUGIN_ID } from './perception/reaction-plugin.js';
|
|
5
6
|
import type { RuntimeEpochPlugin } from '../../framework/plugins/index.js';
|
|
6
7
|
import {
|
|
7
8
|
CLAWCLAW_ACTION_PLUGIN_ID,
|
|
@@ -39,7 +40,7 @@ import {
|
|
|
39
40
|
export interface ClawclawPluginAssemblyOptions {
|
|
40
41
|
epochPlugins?: readonly RuntimeEpochPlugin<Record<string, any>, Record<string, unknown>>[];
|
|
41
42
|
perception?: ClawclawPerceptionConfig;
|
|
42
|
-
behaviorCatalog?: Pick<ClawclawBehaviorCatalog, 'has' | 'prepare'
|
|
43
|
+
behaviorCatalog?: Pick<ClawclawBehaviorCatalog, 'has' | 'prepare'> & Partial<Pick<ClawclawBehaviorCatalog, 'list'>>;
|
|
43
44
|
behaviorDiagnosticsEnabled?: boolean;
|
|
44
45
|
triggerDiagnosticsEnabled?: boolean;
|
|
45
46
|
fallbackBehaviors?: ClawclawRoleFallbackBehaviors;
|
|
@@ -49,6 +50,7 @@ export interface ClawclawPluginAssemblyOptions {
|
|
|
49
50
|
}
|
|
50
51
|
|
|
51
52
|
export interface ClawclawPluginAssembly {
|
|
53
|
+
reactions?: ClawclawReactionPlugin;
|
|
52
54
|
plugins: RuntimeEpochPlugin<Record<string, any>, Record<string, unknown>>[];
|
|
53
55
|
action: ClawclawActionPlugin;
|
|
54
56
|
gameQuery: ClawclawGameQueryPlugin;
|
|
@@ -92,6 +94,8 @@ export function assembleClawclawPlugins(
|
|
|
92
94
|
throw new Error(`Runtime Plugin ${CLAWCLAW_REMINDER_PLUGIN_ID} is not a ClawclawReminderPlugin.`);
|
|
93
95
|
}
|
|
94
96
|
const selected = new Set(options.perception?.modules ?? DEFAULT_PERCEPTION_MODULES);
|
|
97
|
+
const reactionSources = (options.perception?.moduleSources ?? listClawclawPerceptionSources(options.perception?.workspaceDir))
|
|
98
|
+
.filter(source => source.reaction && source.apiVersion === 2 && selected.has(source.id));
|
|
95
99
|
const reminders = configuredReminders as ClawclawReminderPlugin | undefined ?? new ClawclawReminderPlugin({
|
|
96
100
|
sources: (options.perception?.moduleSources ?? listClawclawPerceptionSources(options.perception?.workspaceDir))
|
|
97
101
|
.filter(source => source.reminder && selected.has(source.id)),
|
|
@@ -121,17 +125,29 @@ export function assembleClawclawPlugins(
|
|
|
121
125
|
const trigger = configuredTrigger as ClawclawTriggerPlugin | undefined
|
|
122
126
|
?? new ClawclawTriggerPlugin({
|
|
123
127
|
after: [],
|
|
124
|
-
|
|
128
|
+
// A migrated, selected perception replaces the same declared legacy Trigger.
|
|
129
|
+
// Its old file/config can remain for rollback without evaluating the rule twice.
|
|
130
|
+
triggers: options.triggers?.map(entry => reactionSources.some(source =>
|
|
131
|
+
(source.declaredId ?? source.id) === entry.source.id) ? { ...entry, enabled: false } : entry),
|
|
125
132
|
diagnosticsEnabled: options.triggerDiagnosticsEnabled,
|
|
126
133
|
});
|
|
127
134
|
if (!configuredTrigger) plugins.push(trigger);
|
|
128
135
|
|
|
136
|
+
const reactions = reactionSources.length ? new ClawclawReactionPlugin({
|
|
137
|
+
sources: reactionSources,
|
|
138
|
+
after: [CLAWCLAW_DERIVED_EVENT_PLUGIN_ID, CLAWCLAW_REMINDER_PLUGIN_ID,
|
|
139
|
+
CLAWCLAW_GAME_QUERY_PLUGIN_ID, CLAWCLAW_PERCEPTION_PLUGIN_ID, CLAWCLAW_TRIGGER_PLUGIN_ID],
|
|
140
|
+
behaviors: () => options.behaviorCatalog?.list?.() ?? [],
|
|
141
|
+
}) : undefined;
|
|
142
|
+
if (reactions) plugins.push(reactions);
|
|
143
|
+
|
|
129
144
|
const configuredBehavior = plugins.find((plugin) => plugin.id === CLAWCLAW_BEHAVIOR_PLUGIN_ID);
|
|
130
145
|
if (configuredBehavior && !(configuredBehavior instanceof ClawclawBehaviorPlugin)) {
|
|
131
146
|
throw new Error(`Runtime Plugin ${CLAWCLAW_BEHAVIOR_PLUGIN_ID} is not a ClawclawBehaviorPlugin.`);
|
|
132
147
|
}
|
|
133
148
|
const behavior = configuredBehavior as ClawclawBehaviorPlugin | undefined
|
|
134
149
|
?? new ClawclawBehaviorPlugin({
|
|
150
|
+
perceptionActivations: !!reactions,
|
|
135
151
|
catalog: options.behaviorCatalog ?? new ClawclawBehaviorCatalog([]),
|
|
136
152
|
fallbackBehaviors: options.fallbackBehaviors,
|
|
137
153
|
after: [
|
|
@@ -141,6 +157,7 @@ export function assembleClawclawPlugins(
|
|
|
141
157
|
CLAWCLAW_GAME_QUERY_PLUGIN_ID,
|
|
142
158
|
CLAWCLAW_PERCEPTION_PLUGIN_ID,
|
|
143
159
|
CLAWCLAW_TRIGGER_PLUGIN_ID,
|
|
160
|
+
...(reactions ? [CLAWCLAW_REACTION_PLUGIN_ID] : []),
|
|
144
161
|
],
|
|
145
162
|
eventTypes: options.behaviorEventTypes,
|
|
146
163
|
diagnosticsEnabled: options.behaviorDiagnosticsEnabled,
|
|
@@ -167,5 +184,5 @@ export function assembleClawclawPlugins(
|
|
|
167
184
|
?? new ClawclawMailboxPlugin({ after: eventProducers });
|
|
168
185
|
if (!configuredMailbox) plugins.push(mailbox);
|
|
169
186
|
|
|
170
|
-
return { plugins, action, gameQuery, perception, reminders, trigger, behavior, mailbox };
|
|
187
|
+
return { plugins, action, gameQuery, perception, reminders, trigger, behavior, mailbox, reactions };
|
|
171
188
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { BehaviorActivationLayer } from '../../../../sdk/behavior-plugin/index.js';
|
|
2
2
|
|
|
3
|
-
export type BehaviorActivationSource = 'user' | 'agent' | 'idle' | 'trigger' | 'behavior' | 'system';
|
|
3
|
+
export type BehaviorActivationSource = 'user' | 'agent' | 'idle' | 'trigger' | 'behavior' | 'system' | 'perception';
|
|
4
4
|
export type BehaviorActivationState = 'running' | 'suspended';
|
|
5
5
|
|
|
6
6
|
export interface BehaviorActivationSpec {
|
|
@@ -18,6 +18,8 @@ export interface ClawclawBehaviorCatalogEntry {
|
|
|
18
18
|
readonly apiVersion: number | null;
|
|
19
19
|
readonly expectedApiVersion: typeof BEHAVIOR_PLUGIN_API_VERSION;
|
|
20
20
|
readonly id: string;
|
|
21
|
+
readonly declaredId?: string;
|
|
22
|
+
readonly resourceId?: string;
|
|
21
23
|
readonly name: string;
|
|
22
24
|
readonly description: string;
|
|
23
25
|
readonly localizations?: ResolvedClawclawBehaviorSource['localizations'];
|
|
@@ -45,6 +47,8 @@ function catalogEntry(source: ResolvedClawclawBehaviorSource): ClawclawBehaviorC
|
|
|
45
47
|
apiVersion: source.apiVersion ?? null,
|
|
46
48
|
expectedApiVersion: BEHAVIOR_PLUGIN_API_VERSION,
|
|
47
49
|
id: source.id,
|
|
50
|
+
...(source.declaredId === undefined ? {} : { declaredId: source.declaredId }),
|
|
51
|
+
...(source.resourceId === undefined ? {} : { resourceId: source.resourceId }),
|
|
48
52
|
name: source.name,
|
|
49
53
|
description: source.description,
|
|
50
54
|
...(source.localizations === undefined ? {} : { localizations: source.localizations }),
|
|
@@ -25,6 +25,8 @@ import type {
|
|
|
25
25
|
import { createBehaviorInput } from '../../behavior-input.js';
|
|
26
26
|
import { ClawclawBehaviorObservationMemory } from '../../behavior-observation-memory.js';
|
|
27
27
|
import { isClawclawRuntimeState } from '../../runtime-state.js';
|
|
28
|
+
import { BEHAVIOR_ACTIVATION_CAPABILITY, type PerceptionBehaviorActivation,
|
|
29
|
+
type PerceptionBehaviorActivationResult } from '../../behavior-activation-capability.js';
|
|
28
30
|
import { CLAWCLAW_ACTION_CAPABILITY, CLAWCLAW_ACTION_PLUGIN_ID } from '../action/index.js';
|
|
29
31
|
import { CLAWCLAW_DERIVED_EVENT_PLUGIN_ID } from '../derived-event/index.js';
|
|
30
32
|
import { CLAWCLAW_GAME_QUERY_PLUGIN_ID } from '../game-query/index.js';
|
|
@@ -109,6 +111,7 @@ function isSuccessfulBackendStrategyReport(value: unknown): boolean {
|
|
|
109
111
|
}
|
|
110
112
|
|
|
111
113
|
export interface ClawclawBehaviorPluginOptions {
|
|
114
|
+
readonly perceptionActivations?: boolean;
|
|
112
115
|
readonly catalog: Pick<ClawclawBehaviorCatalog, 'has' | 'prepare'>;
|
|
113
116
|
readonly fallbackBehaviors?: ClawclawRoleFallbackBehaviors;
|
|
114
117
|
readonly manager?: BehaviorActivationManager;
|
|
@@ -124,8 +127,10 @@ export interface ClawclawBehaviorPluginOptions {
|
|
|
124
127
|
}
|
|
125
128
|
|
|
126
129
|
export interface StartBehaviorOptions {
|
|
127
|
-
readonly source: Extract<BehaviorActivationSource, 'agent' | 'user' | 'system'>;
|
|
130
|
+
readonly source: Extract<BehaviorActivationSource, 'agent' | 'user' | 'system' | 'perception'>;
|
|
128
131
|
readonly maxRuntimeMs?: number;
|
|
132
|
+
/** Revalidate scope/phase after asynchronous preparation, before changing control. */
|
|
133
|
+
readonly isCurrent?: () => boolean;
|
|
129
134
|
}
|
|
130
135
|
|
|
131
136
|
export interface ClawclawBehaviorHostStatus {
|
|
@@ -280,7 +285,8 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
|
|
|
280
285
|
readonly after: readonly string[];
|
|
281
286
|
readonly consumes = { events: ['*'] } as const;
|
|
282
287
|
readonly produces: RuntimeEpochPlugin<Record<string, any>>['produces'];
|
|
283
|
-
readonly capabilities
|
|
288
|
+
readonly capabilities: { uses: readonly string[]; provides?: readonly string[] };
|
|
289
|
+
private releasePerceptionActivation?: () => void;
|
|
284
290
|
readonly catchUp: RuntimeEpochCatchUp;
|
|
285
291
|
readonly backlogPolicy = 'finish_started' as const;
|
|
286
292
|
get maxInFlight(): number {
|
|
@@ -327,6 +333,8 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
|
|
|
327
333
|
private backendStrategyReportLifecycleGeneration = 0;
|
|
328
334
|
|
|
329
335
|
constructor(options: ClawclawBehaviorPluginOptions) {
|
|
336
|
+
this.capabilities = { uses: [CLAWCLAW_ACTION_CAPABILITY],
|
|
337
|
+
...(options.perceptionActivations ? { provides: [BEHAVIOR_ACTIVATION_CAPABILITY] } : {}) };
|
|
330
338
|
this.catalog = options.catalog;
|
|
331
339
|
this.fallbackBehaviors = normalizeRoleFallbackBehaviors(options.fallbackBehaviors);
|
|
332
340
|
this.manager = options.manager ?? new BehaviorActivationManager();
|
|
@@ -363,6 +371,49 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
|
|
|
363
371
|
this.scope = context.scope;
|
|
364
372
|
this.diagnostic = context.diagnostic;
|
|
365
373
|
this.stopped = false;
|
|
374
|
+
if (this.capabilities.provides?.includes(BEHAVIOR_ACTIVATION_CAPABILITY)) {
|
|
375
|
+
this.releasePerceptionActivation = context.capabilities.provideAction<PerceptionBehaviorActivation, PerceptionBehaviorActivationResult>({
|
|
376
|
+
capability: BEHAVIOR_ACTIVATION_CAPABILITY,
|
|
377
|
+
describeControl: () => ({ domains: [] }),
|
|
378
|
+
perform: async (request, scope, _caller, execution) => {
|
|
379
|
+
const activationBeforePreparation = this.manager.current();
|
|
380
|
+
const current = () => {
|
|
381
|
+
if (execution.signal.aborted || this.stopped || scope.sessionId !== this.scope?.sessionId
|
|
382
|
+
|| scope.segmentId !== this.scope?.segmentId || request.epochId <= this.lastCommittedEpochSeq) return false;
|
|
383
|
+
const active = this.manager.current();
|
|
384
|
+
if (active?.activationId !== activationBeforePreparation?.activationId
|
|
385
|
+
|| active?.instanceGeneration !== activationBeforePreparation?.instanceGeneration) return false;
|
|
386
|
+
const latest = execution.latestAcceptedState();
|
|
387
|
+
if (!latest) return false;
|
|
388
|
+
const state = latest.state as Record<string, any>;
|
|
389
|
+
const game = isClawclawRuntimeState(state)
|
|
390
|
+
? state.connection === 'connected' && state.stage === 'game' && state.game_snapshot.status === 'fresh'
|
|
391
|
+
? state.game_snapshot.state : undefined
|
|
392
|
+
: state;
|
|
393
|
+
return !!game && game.game_id === request.gameId && game.phase === 'wandering' && game.you?.is_alive === true;
|
|
394
|
+
};
|
|
395
|
+
let value: PerceptionBehaviorActivationResult = { accepted: false, reason: 'stale_request' };
|
|
396
|
+
if (current()) {
|
|
397
|
+
try {
|
|
398
|
+
if (!this.catalog.has(request.behavior)) value = { accepted: false, reason: 'behavior_not_loaded' };
|
|
399
|
+
else if (request.layer === 'reflex') value = await this.requestReflex({
|
|
400
|
+
source: 'trigger', triggerId: `perception:${request.moduleId}:${request.bindingKey}`,
|
|
401
|
+
scope: { sessionId: scope.sessionId, segmentId: scope.segmentId }, epochId: request.epochId,
|
|
402
|
+
configGeneration: 0, behavior: request.behavior, behaviorInput: request.input,
|
|
403
|
+
reflexPriority: request.reflexPriority, maxRuntimeMs: request.maxRuntimeMs ?? 10_000,
|
|
404
|
+
reason: request.reason,
|
|
405
|
+
}, { isCurrent: current });
|
|
406
|
+
else {
|
|
407
|
+
const activation = await this.startLayer(request.layer, request.behavior, request.input,
|
|
408
|
+
{ source: 'perception', maxRuntimeMs: request.maxRuntimeMs, isCurrent: current });
|
|
409
|
+
value = { accepted: true, activationId: activation.activationId };
|
|
410
|
+
}
|
|
411
|
+
} catch { value = { accepted: false, reason: current() ? 'binding_invalid' : 'stale_request' }; }
|
|
412
|
+
}
|
|
413
|
+
return { scope, actionId: randomUUID(), status: 'success', source: 'local', value };
|
|
414
|
+
},
|
|
415
|
+
});
|
|
416
|
+
}
|
|
366
417
|
await this.applyTransitions(this.manager.leaveBoundary(this.now()));
|
|
367
418
|
}
|
|
368
419
|
|
|
@@ -398,12 +449,19 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
|
|
|
398
449
|
});
|
|
399
450
|
}
|
|
400
451
|
|
|
401
|
-
configureFallbackBehaviors(
|
|
452
|
+
configureFallbackBehaviors(
|
|
453
|
+
bindings: ClawclawRoleFallbackBehaviors,
|
|
454
|
+
currentRole?: string,
|
|
455
|
+
): Promise<void> {
|
|
402
456
|
return this.enqueueControl(async () => {
|
|
403
457
|
this.fallbackBehaviors = normalizeRoleFallbackBehaviors(bindings);
|
|
404
458
|
this.fallbackConfigGeneration += 1;
|
|
405
459
|
this.appliedFallbackKey = undefined;
|
|
406
460
|
this.manualFallbackOverride = false;
|
|
461
|
+
// A control receipt must reflect the current role's effective binding,
|
|
462
|
+
// including meetings with no fresh observation frame. The activation
|
|
463
|
+
// manager still owns boundary suspension and explicit long Behaviors.
|
|
464
|
+
await this.syncRoleFallback(currentRole, this.now());
|
|
407
465
|
});
|
|
408
466
|
}
|
|
409
467
|
|
|
@@ -721,6 +779,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
|
|
|
721
779
|
}
|
|
722
780
|
|
|
723
781
|
async stop(reason: 'segment_ending' | 'shutdown'): Promise<void> {
|
|
782
|
+
this.releasePerceptionActivation?.(); this.releasePerceptionActivation = undefined;
|
|
724
783
|
await this.enqueueControl(async () => {
|
|
725
784
|
this.stopped = true;
|
|
726
785
|
this.resetBackendStrategyReporting();
|
|
@@ -760,6 +819,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
|
|
|
760
819
|
return this.enqueueControl(async () => {
|
|
761
820
|
if (this.stopped || !this.scope) throw new Error('behavior_host_not_active');
|
|
762
821
|
const prepared = await this.catalog.prepare(behaviorId, input);
|
|
822
|
+
if (options.isCurrent && !options.isCurrent()) throw new Error('perception_activation_stale');
|
|
763
823
|
const activationId = this.createActivationId();
|
|
764
824
|
const maxRuntimeMs = layer === 'short'
|
|
765
825
|
? runtimeMs(prepared, input, options.maxRuntimeMs) ?? DEFAULT_SHORT_MAX_RUNTIME_MS
|
|
@@ -808,7 +868,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
|
|
|
808
868
|
const now = frameForClock?.nowMs ?? this.now();
|
|
809
869
|
const runtimeState = input.epoch.state;
|
|
810
870
|
|
|
811
|
-
await this.syncRoleFallback(frameForClock, now);
|
|
871
|
+
await this.syncRoleFallback(frameForClock?.gameState.you?.role, now);
|
|
812
872
|
if (
|
|
813
873
|
!frameForClock
|
|
814
874
|
&& isClawclawRuntimeState(runtimeState)
|
|
@@ -1331,10 +1391,9 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
|
|
|
1331
1391
|
}
|
|
1332
1392
|
|
|
1333
1393
|
private async syncRoleFallback(
|
|
1334
|
-
|
|
1394
|
+
role: string | undefined,
|
|
1335
1395
|
now: number,
|
|
1336
1396
|
): Promise<void> {
|
|
1337
|
-
const role = frame?.gameState.you?.role;
|
|
1338
1397
|
if (this.manualFallbackOverride) return;
|
|
1339
1398
|
if (typeof role !== 'string' || !role) return;
|
|
1340
1399
|
const configured = this.fallbackBehaviors.get(role);
|
|
@@ -1404,7 +1463,8 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
|
|
|
1404
1463
|
&& state.connection === 'connected'
|
|
1405
1464
|
&& state.stage === 'game'
|
|
1406
1465
|
&& state.game_snapshot.status === 'fresh'
|
|
1407
|
-
&& state.game_snapshot.state.phase === 'wandering'
|
|
1466
|
+
&& state.game_snapshot.state.phase === 'wandering'
|
|
1467
|
+
&& state.game_snapshot.state.you?.is_alive === true;
|
|
1408
1468
|
|
|
1409
1469
|
const descriptor = this.backendStrategyDescriptor();
|
|
1410
1470
|
const nextTarget = descriptor
|
|
@@ -1423,7 +1483,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
|
|
|
1423
1483
|
}
|
|
1424
1484
|
|
|
1425
1485
|
const target = this.backendStrategyReportTarget;
|
|
1426
|
-
if (!target || this.backendStrategyReportAcknowledgedFingerprint === target.fingerprint) {
|
|
1486
|
+
if (!this.backendStrategyReportEligible || !target || this.backendStrategyReportAcknowledgedFingerprint === target.fingerprint) {
|
|
1427
1487
|
this.clearBackendStrategyReportTimer();
|
|
1428
1488
|
return;
|
|
1429
1489
|
}
|
|
@@ -1467,7 +1527,6 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
|
|
|
1467
1527
|
|| this.backendStrategyReportInFlight
|
|
1468
1528
|
) return;
|
|
1469
1529
|
if (!this.backendStrategyReportEligible || !context || context.signal.aborted) {
|
|
1470
|
-
this.scheduleBackendStrategyReport(BACKEND_STRATEGY_REPORT_RETRY_MS);
|
|
1471
1530
|
return;
|
|
1472
1531
|
}
|
|
1473
1532
|
|
|
@@ -1528,6 +1587,10 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
|
|
|
1528
1587
|
}
|
|
1529
1588
|
|
|
1530
1589
|
if (target?.fingerprint === attempt.fingerprint) {
|
|
1590
|
+
if (!this.backendStrategyReportEligible) {
|
|
1591
|
+
this.clearBackendStrategyReportTimer();
|
|
1592
|
+
return;
|
|
1593
|
+
}
|
|
1531
1594
|
this.backendStrategyReportContext?.diagnostic('strategy.report.retry_scheduled', {
|
|
1532
1595
|
strategy_id: target.id,
|
|
1533
1596
|
retry_ms: BACKEND_STRATEGY_REPORT_RETRY_MS,
|
|
@@ -63,6 +63,8 @@ export interface ResolvedClawclawBehaviorSource {
|
|
|
63
63
|
readonly id: string;
|
|
64
64
|
/** Host-assigned operation names never change the ID in the source file. */
|
|
65
65
|
readonly declaredId?: string;
|
|
66
|
+
/** Host-only Hub identity used for optional perception dependency preferences. */
|
|
67
|
+
readonly resourceId?: string;
|
|
66
68
|
readonly workingCopyPath?: string;
|
|
67
69
|
readonly name: string;
|
|
68
70
|
readonly display?: Readonly<{ name: string; description: string }>;
|
|
@@ -327,7 +327,7 @@ function createModuleSlots(
|
|
|
327
327
|
const source = sources.get(id);
|
|
328
328
|
if (!source) throw new Error(`Unknown perception module '${id}'.`);
|
|
329
329
|
return source;
|
|
330
|
-
}).filter(source => !source.reminder);
|
|
330
|
+
}).filter(source => !source.reminder && !source.reaction);
|
|
331
331
|
const reducerPool = selected.length > 0
|
|
332
332
|
? new PerceptionReducerThreadPool({
|
|
333
333
|
modules: selected.map((source) => loader.threadSpec(source)),
|
|
@@ -25,11 +25,13 @@ import { literalPluginApiVersion } from '../plugin-api-version.js';
|
|
|
25
25
|
import { parseLiteralModuleManifest } from '../behavior-input-source.js';
|
|
26
26
|
import { normalizeReminderManifest } from '../../reminder-manifest.js';
|
|
27
27
|
import type { ClawclawReminderManifest } from '../../../../sdk/perception-plugin/reminder.js';
|
|
28
|
+
import type { ClawclawReactionManifest } from '../../../../sdk/perception-plugin/reaction.js';
|
|
29
|
+
import { normalizeReactionManifest } from '../../reaction-manifest.js';
|
|
28
30
|
|
|
29
31
|
export const MAX_PERCEPTION_FILES = 512;
|
|
30
32
|
const MAX_PERCEPTION_SOURCE_BYTES = 2 * 1024 * 1024;
|
|
31
33
|
const SAFE_IMPORT = /(?:@myclaw163\/clawclaw-cli|clawclaw-cli)\/perception-plugin/;
|
|
32
|
-
const DEFAULT_CLASS = /export\s+default\s+class(?:\s+[A-Za-z_$][\w$]*)?\s+extends\s+(ClawclawPerception|ClawclawParallelPerception|ClawclawReminder)(?:\s*<[^>{}]*>)?\s*\{/;
|
|
34
|
+
const DEFAULT_CLASS = /export\s+default\s+class(?:\s+[A-Za-z_$][\w$]*)?\s+extends\s+(ClawclawPerception|ClawclawParallelPerception|ClawclawReminder|ClawclawReaction)(?:\s*<[^>{}]*>)?\s*\{/;
|
|
33
35
|
const STATIC_MANIFEST = /\bstatic\s+(?:readonly\s+)?manifest\s*=\s*\{/;
|
|
34
36
|
|
|
35
37
|
export interface ResolvedClawclawPerceptionSource {
|
|
@@ -44,6 +46,7 @@ export interface ResolvedClawclawPerceptionSource {
|
|
|
44
46
|
readonly manifest: ClawclawPerceptionManifest;
|
|
45
47
|
/** Non-visual execution contract; manifest above is the common resource descriptor. */
|
|
46
48
|
readonly reminder?: ClawclawReminderManifest;
|
|
49
|
+
readonly reaction?: ClawclawReactionManifest;
|
|
47
50
|
readonly sourcePath: string;
|
|
48
51
|
readonly sourceRoot: string;
|
|
49
52
|
}
|
|
@@ -348,6 +351,16 @@ function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPe
|
|
|
348
351
|
const manifestBlock = balancedBlock(classBody, manifestOpen, '{', '}');
|
|
349
352
|
if (!manifestBlock) return null;
|
|
350
353
|
|
|
354
|
+
if (classMatch[1] === 'ClawclawReaction') {
|
|
355
|
+
try {
|
|
356
|
+
const reaction = normalizeReactionManifest(parseLiteralModuleManifest(manifestBlock), false);
|
|
357
|
+
const { id, description, localizations } = reaction;
|
|
358
|
+
const name = reaction.name ?? id;
|
|
359
|
+
return { apiVersion: reaction.apiVersion, id, name, description, reaction, sourcePath, sourceRoot,
|
|
360
|
+
manifest: { apiVersion: reaction.apiVersion, id, name, description, localizations,
|
|
361
|
+
subjectScope: 'self_and_others', produces: [] } };
|
|
362
|
+
} catch { return null; }
|
|
363
|
+
}
|
|
351
364
|
if (classMatch[1] === 'ClawclawReminder') {
|
|
352
365
|
try {
|
|
353
366
|
const reminder = normalizeReminderManifest(parseLiteralModuleManifest(manifestBlock), false);
|