Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(engine-scope): run each operation and persistence consumer in its engine's scope

garrytan4bea98188ef9
diff --git a/src/core/engine-scope.ts b/src/core/engine-scope.ts
new file mode 100644
index 0000000000..c10789004b
--- /dev/null
+++ b/src/core/engine-scope.ts
@@ -0,0 +1,25 @@
+/**
+ * Which engine a call runs for, for code that reads per-engine state without taking the engine as an argument: the
+ * AI gateway (ai/gateway.ts) and the Anthropic key resolver (ai/anthropic-key.ts). Every operation handler runs inside
+ * its context's engine scope (operation-load.ts), and so does each persistence consumer (persistence/service.ts).
+ * A host that calls core functions directly, outside an operation, wraps them in `withEngineScope(engine, fn)`.
+ *
+ * Only an engine `openEngine` opened changes anything: for every other engine, and in a process that never opened
+ * one, the gateway keeps its process-wide state exactly as before, and no scope is even entered.
+ */
+import { AsyncLocalStorage } from 'node:async_hooks';
+import { isEmbeddedEngine, processHasEmbeddedEngines } from './embedded-engine.ts';
+
+const scope = new AsyncLocalStorage<object>();
+
+/** Runs `fn` as a call for `engine`. A plain call in a process that holds no embedded engine. */
+export function withEngineScope<T>(engine: object, fn: () => T): T {
+ return processHasEmbeddedEngines() ? scope.run(engine, fn) : fn();
+}
+
+/** The embedded engine the current call runs for (a page transaction, view or proxy over one counts), else undefined. */
+export function embeddedEngineInScope(): object | undefined {
+ if (!processHasEmbeddedEngines()) return undefined;
+ const engine = scope.getStore();
+ return engine && isEmbeddedEngine(engine) ? engine : undefined;
+}
diff --git a/src/core/operation-load.ts b/src/core/operation-load.ts
index eb862e74e0..bd7b700761 100644
--- a/src/core/operation-load.ts
+++ b/src/core/operation-load.ts
@@ -11,6 +11,7 @@
*/
import type { Operation } from './ops/contract.ts';
import { withOutputRedaction } from './search/output-redaction.ts';
+import { withEngineScope } from './engine-scope.ts';
import { OPERATION_LOADERS } from './operation-loaders.generated.ts';
// ---------------------------------------------------------------------------
@@ -124,7 +125,9 @@ export function finalizeOperation(op: Operation): void {
if (op.area === undefined && OP_AREAS[op.name] !== undefined) {
op.area = OP_AREAS[op.name];
}
- op.handler = withOutputRedaction(op);
+ // The handler runs in its engine's scope, so an embedded engine's AI calls use that engine's gateway (engine-scope.ts).
+ const handler = withOutputRedaction(op);
+ op.handler = (ctx, params) => withEngineScope(ctx.engine, () => handler(ctx, params));
}
/** The finalized operation named `name`, loading only the module that defines it. */
diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.ts
index 267b1229d9..bd9a910aab 100644
--- a/src/core/persistence/service.ts
+++ b/src/core/persistence/service.ts
@@ -8,6 +8,7 @@ import { RESIDENT_CONSUMER_KINDS, startConsumerHeartbeat, type ConsumerHeartbeat
import { enginePoolStats } from '../postgres-engine/pool-stats.ts';
import { claimOwnerKind, isOneShotCommand } from './claim-phase.ts';
import { noteDirectPoolLease } from '../direct-pool-profile.ts';
+import { withEngineScope } from '../engine-scope.ts';
import { preparePageMutation } from './page-prepare.ts';
import { prepareSemanticPageMutation } from './semantic-pages.ts';
import { getWriteRequestById, getWriteRequestProgress, receiptFor, type WriteRequestProgress } from './journal.ts';
@@ -151,7 +152,8 @@ export function startPersistenceConsumer(engine: BrainEngine, config: GBrainConf
// An explicit switch to another datastore must not inherit the old brain's config.
if (sameDatastore) startPersistenceConsumer(engine, config);
});
- consumer.start();
+ // The consumer's publications (embeddings included) run in its engine's scope (engine-scope.ts).
+ withEngineScope(engine, () => consumer.start());
return consumer;
}
export async function stopPersistenceConsumer(engine: BrainEngine): Promise<void> {