mirror of
https://github.com/moltbot/moltbot.git
synced 2026-03-07 22:44:16 +00:00
* feat(context-engine): add ContextEngine interface and registry
Introduce the pluggable ContextEngine abstraction that allows external
plugins to register custom context management strategies.
- ContextEngine interface with lifecycle methods: bootstrap, ingest,
ingestBatch, afterTurn, assemble, compact, prepareSubagentSpawn,
onSubagentEnded, dispose
- Module-level singleton registry with registerContextEngine() and
resolveContextEngine() (config-driven slot selection)
- LegacyContextEngine: pass-through implementation wrapping existing
compaction behavior for 100% backward compatibility
- ensureContextEnginesInitialized() guard for safe one-time registration
- 19 tests covering contract, registry, resolution, and legacy parity
* feat(plugins): add context-engine slot and registerContextEngine API
Wire the ContextEngine abstraction into the plugin system so external
plugins can register context engines via the standard plugin API.
- Add 'context-engine' to PluginKind union type
- Add 'contextEngine' slot to PluginSlotsConfig (default: 'legacy')
- Wire registerContextEngine() through OpenClawPluginApi
- Export ContextEngine types from plugin-sdk for external consumers
- Restore proper slot-based resolution in registry
* feat(context-engine): wire ContextEngine into agent run lifecycle
Integrate the ContextEngine abstraction into the core agent run path:
- Resolve context engine once per run (reused across retries)
- Bootstrap: hydrate canonical store from session file on first run
- Assemble: route context assembly through pluggable engine
- Auto-compaction guard: disable built-in auto-compaction when
the engine declares ownsCompaction (prevents double-compaction)
- AfterTurn: post-turn lifecycle hook for ingest + background
compaction decisions
- Overflow compaction: route through contextEngine.compact()
- Dispose: clean up engine resources in finally block
- Notify context engine on subagent lifecycle events
Legacy engine: all lifecycle methods are pass-through/no-op, preserving
100% backward compatibility for users without a context engine plugin.
* feat(plugins): add scoped subagent methods and gateway request scope
Expose runtime.subagent.{run, waitForRun, getSession, deleteSession}
so external plugins can spawn sub-agent sessions without raw gateway
dispatch access.
Uses AsyncLocalStorage request-scope bridge to dispatch internally via
handleGatewayRequest with a synthetic operator client. Methods are only
available during gateway request handling.
- Symbol.for-backed global singleton for cross-module-reload safety
- Fallback gateway context for non-WS dispatch paths (Telegram/WhatsApp)
- Set gateway request scope for all handlers, not just plugin handlers
- 3 staleness tests for fallback context hardening
* feat(context-engine): route /compact and sessions.get through context engine
Wire the /compact command and sessions.get handler through the pluggable
ContextEngine interface.
- Thread tokenBudget and force parameters to context engine compact
- Route /compact through contextEngine.compact() when registered
- Wire sessions.get as runtime alias for plugin subagent dispatch
- Add .pebbles/ to .gitignore
* style: format with oxfmt 0.33.0
Fix duplicate import (ControlUiRootState in server.impl.ts) and
import ordering across all changed files.
* fix: update extension test mocks for context-engine types
Add missing subagent property to bluebubbles PluginRuntime mock.
Add missing registerContextEngine to lobster OpenClawPluginApi mock.
* fix(subagents): keep deferred delete cleanup retryable
* style: format run attempt for CI
* fix(rebase): remove duplicate embedded-run imports
* test: add missing gateway context mock export
* fix: pass resolved auth profile into afterTurn compaction
Ensure the embedded runner forwards resolved auth profile context into
legacy context-engine compaction params on the normal afterTurn path,
matching overflow compaction behavior. This allows downstream LCM
summarization to use the intended provider auth/profile consistently.
Also fix strict TS typing in external-link token dedupe and align an
attempt unit test reasoningLevel value with the current ReasoningLevel
enum.
Regeneration-Prompt: |
We were debugging context-engine compaction where downstream summary
calls were missing the right auth/profile context in normal afterTurn
flow, while overflow compaction already propagated it. Preserve current
behavior and keep changes additive: thread the resolved authProfileId
through run -> attempt -> legacy compaction param builder without
broad refactors.
Add tests that prove the auth profile is included in afterTurn legacy
params and that overflow compaction still passes it through run
attempts. Keep existing APIs stable, and only adjust small type issues
needed for strict compilation.
* fix: remove duplicate imports from rebase
* feat: add context-engine system prompt additions
* fix(rebase): dedupe attempt import declarations
* test: fix fetch mock typing in ollama autodiscovery
* fix(test): add registerContextEngine to diffs extension mock APIs
* test(windows): use path.delimiter in ios-team-id fixture PATH
* test(cron): add model formatting and precedence edge case tests
Covers:
- Provider/model string splitting (whitespace, nested paths, empty segments)
- Provider normalization (casing, aliases like bedrock→amazon-bedrock)
- Anthropic model alias normalization (opus-4.5→claude-opus-4-5)
- Precedence: job payload > session override > config default
- Sequential runs with different providers (CI flake regression pattern)
- forceNew session preserving stored model overrides
- Whitespace/empty model string edge cases
- Config model as string vs object format
* test(cron): fix model formatting test config types
* test(phone-control): add registerContextEngine to mock API
* fix: re-export ChannelKind from config-reload-plan
* fix: add subagent mock to plugin-runtime-mock test util
* docs: add changelog fragment for context engine PR #22201
256 lines
11 KiB
TypeScript
256 lines
11 KiB
TypeScript
import type { PluginRuntime } from "openclaw/plugin-sdk/test-utils";
|
|
import { removeAckReactionAfterReply, shouldAckReaction } from "openclaw/plugin-sdk/test-utils";
|
|
import { vi } from "vitest";
|
|
|
|
type DeepPartial<T> = {
|
|
[K in keyof T]?: T[K] extends (...args: never[]) => unknown
|
|
? T[K]
|
|
: T[K] extends ReadonlyArray<unknown>
|
|
? T[K]
|
|
: T[K] extends object
|
|
? DeepPartial<T[K]>
|
|
: T[K];
|
|
};
|
|
|
|
function isObject(value: unknown): value is Record<string, unknown> {
|
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
}
|
|
|
|
function mergeDeep<T>(base: T, overrides: DeepPartial<T>): T {
|
|
const result: Record<string, unknown> = { ...(base as Record<string, unknown>) };
|
|
for (const [key, overrideValue] of Object.entries(overrides as Record<string, unknown>)) {
|
|
if (overrideValue === undefined) {
|
|
continue;
|
|
}
|
|
const baseValue = result[key];
|
|
if (isObject(baseValue) && isObject(overrideValue)) {
|
|
result[key] = mergeDeep(baseValue, overrideValue);
|
|
continue;
|
|
}
|
|
result[key] = overrideValue;
|
|
}
|
|
return result as T;
|
|
}
|
|
|
|
export function createPluginRuntimeMock(overrides: DeepPartial<PluginRuntime> = {}): PluginRuntime {
|
|
const base: PluginRuntime = {
|
|
version: "1.0.0-test",
|
|
config: {
|
|
loadConfig: vi.fn(() => ({})) as unknown as PluginRuntime["config"]["loadConfig"],
|
|
writeConfigFile: vi.fn() as unknown as PluginRuntime["config"]["writeConfigFile"],
|
|
},
|
|
system: {
|
|
enqueueSystemEvent: vi.fn() as unknown as PluginRuntime["system"]["enqueueSystemEvent"],
|
|
requestHeartbeatNow: vi.fn() as unknown as PluginRuntime["system"]["requestHeartbeatNow"],
|
|
runCommandWithTimeout: vi.fn() as unknown as PluginRuntime["system"]["runCommandWithTimeout"],
|
|
formatNativeDependencyHint: vi.fn(
|
|
() => "",
|
|
) as unknown as PluginRuntime["system"]["formatNativeDependencyHint"],
|
|
},
|
|
media: {
|
|
loadWebMedia: vi.fn() as unknown as PluginRuntime["media"]["loadWebMedia"],
|
|
detectMime: vi.fn() as unknown as PluginRuntime["media"]["detectMime"],
|
|
mediaKindFromMime: vi.fn() as unknown as PluginRuntime["media"]["mediaKindFromMime"],
|
|
isVoiceCompatibleAudio:
|
|
vi.fn() as unknown as PluginRuntime["media"]["isVoiceCompatibleAudio"],
|
|
getImageMetadata: vi.fn() as unknown as PluginRuntime["media"]["getImageMetadata"],
|
|
resizeToJpeg: vi.fn() as unknown as PluginRuntime["media"]["resizeToJpeg"],
|
|
},
|
|
tts: {
|
|
textToSpeechTelephony: vi.fn() as unknown as PluginRuntime["tts"]["textToSpeechTelephony"],
|
|
},
|
|
stt: {
|
|
transcribeAudioFile: vi.fn() as unknown as PluginRuntime["stt"]["transcribeAudioFile"],
|
|
},
|
|
tools: {
|
|
createMemoryGetTool: vi.fn() as unknown as PluginRuntime["tools"]["createMemoryGetTool"],
|
|
createMemorySearchTool:
|
|
vi.fn() as unknown as PluginRuntime["tools"]["createMemorySearchTool"],
|
|
registerMemoryCli: vi.fn() as unknown as PluginRuntime["tools"]["registerMemoryCli"],
|
|
},
|
|
channel: {
|
|
text: {
|
|
chunkByNewline: vi.fn((text: string) => (text ? [text] : [])),
|
|
chunkMarkdownText: vi.fn((text: string) => [text]),
|
|
chunkMarkdownTextWithMode: vi.fn((text: string) => (text ? [text] : [])),
|
|
chunkText: vi.fn((text: string) => (text ? [text] : [])),
|
|
chunkTextWithMode: vi.fn((text: string) => (text ? [text] : [])),
|
|
resolveChunkMode: vi.fn(
|
|
() => "length",
|
|
) as unknown as PluginRuntime["channel"]["text"]["resolveChunkMode"],
|
|
resolveTextChunkLimit: vi.fn(() => 4000),
|
|
hasControlCommand: vi.fn(() => false),
|
|
resolveMarkdownTableMode: vi.fn(
|
|
() => "code",
|
|
) as unknown as PluginRuntime["channel"]["text"]["resolveMarkdownTableMode"],
|
|
convertMarkdownTables: vi.fn((text: string) => text),
|
|
},
|
|
reply: {
|
|
dispatchReplyWithBufferedBlockDispatcher: vi.fn(
|
|
async () => undefined,
|
|
) as unknown as PluginRuntime["channel"]["reply"]["dispatchReplyWithBufferedBlockDispatcher"],
|
|
createReplyDispatcherWithTyping:
|
|
vi.fn() as unknown as PluginRuntime["channel"]["reply"]["createReplyDispatcherWithTyping"],
|
|
resolveEffectiveMessagesConfig:
|
|
vi.fn() as unknown as PluginRuntime["channel"]["reply"]["resolveEffectiveMessagesConfig"],
|
|
resolveHumanDelayConfig:
|
|
vi.fn() as unknown as PluginRuntime["channel"]["reply"]["resolveHumanDelayConfig"],
|
|
dispatchReplyFromConfig:
|
|
vi.fn() as unknown as PluginRuntime["channel"]["reply"]["dispatchReplyFromConfig"],
|
|
withReplyDispatcher: vi.fn(async ({ dispatcher, run, onSettled }) => {
|
|
try {
|
|
return await run();
|
|
} finally {
|
|
dispatcher.markComplete();
|
|
try {
|
|
await dispatcher.waitForIdle();
|
|
} finally {
|
|
await onSettled?.();
|
|
}
|
|
}
|
|
}) as unknown as PluginRuntime["channel"]["reply"]["withReplyDispatcher"],
|
|
finalizeInboundContext: vi.fn(
|
|
(ctx: Record<string, unknown>) => ctx,
|
|
) as unknown as PluginRuntime["channel"]["reply"]["finalizeInboundContext"],
|
|
formatAgentEnvelope: vi.fn(
|
|
(opts: { body: string }) => opts.body,
|
|
) as unknown as PluginRuntime["channel"]["reply"]["formatAgentEnvelope"],
|
|
formatInboundEnvelope: vi.fn(
|
|
(opts: { body: string }) => opts.body,
|
|
) as unknown as PluginRuntime["channel"]["reply"]["formatInboundEnvelope"],
|
|
resolveEnvelopeFormatOptions: vi.fn(() => ({
|
|
template: "channel+name+time",
|
|
})) as unknown as PluginRuntime["channel"]["reply"]["resolveEnvelopeFormatOptions"],
|
|
},
|
|
routing: {
|
|
resolveAgentRoute: vi.fn(() => ({
|
|
agentId: "main",
|
|
accountId: "default",
|
|
sessionKey: "agent:main:test:dm:peer",
|
|
})) as unknown as PluginRuntime["channel"]["routing"]["resolveAgentRoute"],
|
|
},
|
|
pairing: {
|
|
buildPairingReply: vi.fn(
|
|
() => "Pairing code: TESTCODE",
|
|
) as unknown as PluginRuntime["channel"]["pairing"]["buildPairingReply"],
|
|
readAllowFromStore: vi
|
|
.fn()
|
|
.mockResolvedValue(
|
|
[],
|
|
) as unknown as PluginRuntime["channel"]["pairing"]["readAllowFromStore"],
|
|
upsertPairingRequest: vi.fn().mockResolvedValue({
|
|
code: "TESTCODE",
|
|
created: true,
|
|
}) as unknown as PluginRuntime["channel"]["pairing"]["upsertPairingRequest"],
|
|
},
|
|
media: {
|
|
fetchRemoteMedia:
|
|
vi.fn() as unknown as PluginRuntime["channel"]["media"]["fetchRemoteMedia"],
|
|
saveMediaBuffer: vi.fn().mockResolvedValue({
|
|
path: "/tmp/test-media.jpg",
|
|
contentType: "image/jpeg",
|
|
}) as unknown as PluginRuntime["channel"]["media"]["saveMediaBuffer"],
|
|
},
|
|
session: {
|
|
resolveStorePath: vi.fn(
|
|
() => "/tmp/sessions.json",
|
|
) as unknown as PluginRuntime["channel"]["session"]["resolveStorePath"],
|
|
readSessionUpdatedAt: vi.fn(
|
|
() => undefined,
|
|
) as unknown as PluginRuntime["channel"]["session"]["readSessionUpdatedAt"],
|
|
recordSessionMetaFromInbound:
|
|
vi.fn() as unknown as PluginRuntime["channel"]["session"]["recordSessionMetaFromInbound"],
|
|
recordInboundSession:
|
|
vi.fn() as unknown as PluginRuntime["channel"]["session"]["recordInboundSession"],
|
|
updateLastRoute:
|
|
vi.fn() as unknown as PluginRuntime["channel"]["session"]["updateLastRoute"],
|
|
},
|
|
mentions: {
|
|
buildMentionRegexes: vi.fn(() => [
|
|
/\bbert\b/i,
|
|
]) as unknown as PluginRuntime["channel"]["mentions"]["buildMentionRegexes"],
|
|
matchesMentionPatterns: vi.fn((text: string, regexes: RegExp[]) =>
|
|
regexes.some((regex) => regex.test(text)),
|
|
) as unknown as PluginRuntime["channel"]["mentions"]["matchesMentionPatterns"],
|
|
matchesMentionWithExplicit: vi.fn(
|
|
(params: { text: string; mentionRegexes: RegExp[]; explicitWasMentioned?: boolean }) =>
|
|
params.explicitWasMentioned === true
|
|
? true
|
|
: params.mentionRegexes.some((regex) => regex.test(params.text)),
|
|
) as unknown as PluginRuntime["channel"]["mentions"]["matchesMentionWithExplicit"],
|
|
},
|
|
reactions: {
|
|
shouldAckReaction,
|
|
removeAckReactionAfterReply,
|
|
},
|
|
groups: {
|
|
resolveGroupPolicy: vi.fn(
|
|
() => "open",
|
|
) as unknown as PluginRuntime["channel"]["groups"]["resolveGroupPolicy"],
|
|
resolveRequireMention: vi.fn(
|
|
() => false,
|
|
) as unknown as PluginRuntime["channel"]["groups"]["resolveRequireMention"],
|
|
},
|
|
debounce: {
|
|
createInboundDebouncer: vi.fn(
|
|
(params: { onFlush: (items: unknown[]) => Promise<void> }) => ({
|
|
enqueue: async (item: unknown) => {
|
|
await params.onFlush([item]);
|
|
},
|
|
flushKey: vi.fn(),
|
|
}),
|
|
) as unknown as PluginRuntime["channel"]["debounce"]["createInboundDebouncer"],
|
|
resolveInboundDebounceMs: vi.fn(
|
|
() => 0,
|
|
) as unknown as PluginRuntime["channel"]["debounce"]["resolveInboundDebounceMs"],
|
|
},
|
|
commands: {
|
|
resolveCommandAuthorizedFromAuthorizers: vi.fn(
|
|
() => false,
|
|
) as unknown as PluginRuntime["channel"]["commands"]["resolveCommandAuthorizedFromAuthorizers"],
|
|
isControlCommandMessage:
|
|
vi.fn() as unknown as PluginRuntime["channel"]["commands"]["isControlCommandMessage"],
|
|
shouldComputeCommandAuthorized:
|
|
vi.fn() as unknown as PluginRuntime["channel"]["commands"]["shouldComputeCommandAuthorized"],
|
|
shouldHandleTextCommands:
|
|
vi.fn() as unknown as PluginRuntime["channel"]["commands"]["shouldHandleTextCommands"],
|
|
},
|
|
discord: {} as PluginRuntime["channel"]["discord"],
|
|
activity: {} as PluginRuntime["channel"]["activity"],
|
|
line: {} as PluginRuntime["channel"]["line"],
|
|
slack: {} as PluginRuntime["channel"]["slack"],
|
|
telegram: {} as PluginRuntime["channel"]["telegram"],
|
|
signal: {} as PluginRuntime["channel"]["signal"],
|
|
imessage: {} as PluginRuntime["channel"]["imessage"],
|
|
whatsapp: {} as PluginRuntime["channel"]["whatsapp"],
|
|
},
|
|
events: {
|
|
onAgentEvent: vi.fn(() => () => {}) as unknown as PluginRuntime["events"]["onAgentEvent"],
|
|
onSessionTranscriptUpdate: vi.fn(
|
|
() => () => {},
|
|
) as unknown as PluginRuntime["events"]["onSessionTranscriptUpdate"],
|
|
},
|
|
logging: {
|
|
shouldLogVerbose: vi.fn(() => false),
|
|
getChildLogger: vi.fn(() => ({
|
|
info: vi.fn(),
|
|
warn: vi.fn(),
|
|
error: vi.fn(),
|
|
debug: vi.fn(),
|
|
})),
|
|
},
|
|
state: {
|
|
resolveStateDir: vi.fn(() => "/tmp/openclaw"),
|
|
},
|
|
subagent: {
|
|
run: vi.fn(),
|
|
waitForRun: vi.fn(),
|
|
getSessionMessages: vi.fn(),
|
|
getSession: vi.fn(),
|
|
deleteSession: vi.fn(),
|
|
},
|
|
};
|
|
|
|
return mergeDeep(base, overrides);
|
|
}
|