ACP: harden startup and move configured routing behind plugin seams (#48197)
* ACPX: keep plugin-local runtime installs out of dist * Gateway: harden ACP startup and service PATH * ACP: reinitialize error-state configured bindings * ACP: classify pre-turn runtime failures as session init failures * Plugins: move configured ACP routing behind channel seams * Telegram tests: align startup probe assertions after rebase * Discord: harden ACP configured binding recovery * ACP: recover Discord bindings after stale runtime exits * ACPX: replace dead sessions during ensure * Discord: harden ACP binding recovery * Discord: fix review follow-ups * ACP bindings: load channel snapshots across workspaces * ACP bindings: cache snapshot channel plugin resolution * Experiments: add ACP pluginification holy grail plan * Experiments: rename ACP pluginification plan doc * Experiments: drop old ACP pluginification doc path * ACP: move configured bindings behind plugin services * Experiments: update bindings capability architecture plan * Bindings: isolate configured binding routing and targets * Discord tests: fix runtime env helper path * Tests: fix channel binding CI regressions * Tests: normalize ACP workspace assertion on Windows * Bindings: isolate configured binding registry * Bindings: finish configured binding cleanup * Bindings: finish generic cleanup * Bindings: align runtime approval callbacks * ACP: delete residual bindings barrel * Bindings: restore legacy compatibility * Revert "Bindings: restore legacy compatibility" This reverts commit ac2ed68fa2426ecc874d68278c71c71ad363fcfe. * Tests: drop ACP route legacy helper names * Discord/ACP: fix binding regressions --------- Co-authored-by: Onur <2453968+osolmaz@users.noreply.github.com>feature/PAZ-358-fe-credit-error-display
parent
8139f83175
commit
ea15819ecf
@ -0,0 +1,519 @@
|
||||
# Bindings Capability Architecture Plan
|
||||
|
||||
Status: in progress
|
||||
|
||||
## Summary
|
||||
|
||||
The goal is not to move all ACP code out of core.
|
||||
|
||||
The goal is to make `bindings` a small core capability, keep the ACP session kernel in core, and move ACP-specific binding policy plus codex app server policy out of core.
|
||||
|
||||
That gives us a lightweight core without hiding core semantics behind plugin indirection.
|
||||
|
||||
## Current Conclusion
|
||||
|
||||
The current architecture should converge on this split:
|
||||
|
||||
- Core owns the generic binding capability.
|
||||
- Core owns the generic ACP session kernel.
|
||||
- Channel plugins own channel-specific binding semantics.
|
||||
- ACP backend plugins own runtime protocol details.
|
||||
- Product-level consumers like ACP configured bindings and the codex app server sit on top of the binding capability instead of hardcoding their own binding plumbing.
|
||||
|
||||
This is different from "everything becomes a plugin".
|
||||
|
||||
## Why This Changed
|
||||
|
||||
The current codebase already shows that there are really three different layers:
|
||||
|
||||
- binding and conversation ownership
|
||||
- long-lived session and runtime-handle orchestration
|
||||
- product-specific turn logic
|
||||
|
||||
Those layers should not all be forced into one runtime engine.
|
||||
|
||||
Today the duplication is mostly in the execution/control-plane shape, not in storage or binding plumbing:
|
||||
|
||||
- the main harness has its own turn engine
|
||||
- ACP has its own session control plane
|
||||
- the codex app server plugin path likely owns its own app-level turn engine outside this repo
|
||||
|
||||
The right move is to share the stable control-plane contracts, not to force all three into one giant executor.
|
||||
|
||||
## Verified Current State
|
||||
|
||||
### Generic binding pieces already exist
|
||||
|
||||
- `src/infra/outbound/session-binding-service.ts` already provides a generic binding store and adapter model.
|
||||
- `src/plugins/conversation-binding.ts` already lets plugins request a conversation binding and stores plugin-owned binding metadata.
|
||||
- `src/plugins/types.ts` already exposes plugin-facing binding APIs.
|
||||
- `src/plugins/types.ts` already exposes the generic `inbound_claim` hook.
|
||||
|
||||
### ACP is only partially pluginified
|
||||
|
||||
- `src/channels/plugins/configured-binding-registry.ts` now owns generic configured binding compilation and lookup.
|
||||
- `src/channels/plugins/binding-routing.ts` and `src/channels/plugins/binding-targets.ts` now own the generic route and target lifecycle seams.
|
||||
- ACP now plugs into that seam through `src/channels/plugins/acp-configured-binding-consumer.ts` and `src/channels/plugins/acp-stateful-target-driver.ts`.
|
||||
- `src/acp/persistent-bindings.lifecycle.ts` still owns configured ACP ensure and reset behavior.
|
||||
- runtime-created plugin conversation bindings still use a separate path in `src/plugins/conversation-binding.ts`.
|
||||
|
||||
### Codex app server is already closer to the desired shape
|
||||
|
||||
From this repo's side, the codex app server path is much thinner:
|
||||
|
||||
- a plugin binds a conversation
|
||||
- core stores that binding
|
||||
- inbound dispatch targets the plugin's `inbound_claim` hook
|
||||
|
||||
What core does not provide for the codex app server path is an ACP-like shared session kernel. If the app server needs retries, long-lived runtime handles, cancellation, or session health logic, it must own that itself today.
|
||||
|
||||
## The Durable Split
|
||||
|
||||
### 1. Core Binding Capability
|
||||
|
||||
This should become the primary shared seam.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- canonical `ConversationRef`
|
||||
- binding record storage
|
||||
- configured binding compilation
|
||||
- runtime-created binding storage
|
||||
- fast binding lookup on inbound
|
||||
- binding touch/unbind lifecycle
|
||||
- generic dispatch handoff to the binding target
|
||||
|
||||
What core binding capability must not own:
|
||||
|
||||
- Discord thread rules
|
||||
- Telegram topic rules
|
||||
- Feishu chat rules
|
||||
- ACP session orchestration
|
||||
- codex app server business logic
|
||||
|
||||
### 2. Core Stateful Target Kernel
|
||||
|
||||
This is the small generic kernel for long-lived bound targets.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- ensure target ready
|
||||
- run turn
|
||||
- cancel turn
|
||||
- close target
|
||||
- reset target
|
||||
- status and health
|
||||
- persistence of target metadata
|
||||
- retries and runtime-handle safety
|
||||
- per-target serialization and concurrency
|
||||
|
||||
ACP is the first real implementation of this shape.
|
||||
|
||||
This kernel should stay in core because it is mandatory infrastructure and has strict startup, reset, and recovery semantics.
|
||||
|
||||
### 3. Channel Binding Providers
|
||||
|
||||
Each channel plugin should own the meaning of "this channel conversation maps to this binding rule".
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- normalize configured binding targets
|
||||
- normalize inbound conversations
|
||||
- match inbound conversations against compiled bindings
|
||||
- define channel-specific matching priority
|
||||
- optionally provide binding description text for status and logs
|
||||
|
||||
This is where Discord channel vs thread logic, Telegram topic rules, and Feishu conversation rules belong.
|
||||
|
||||
### 4. Product Consumers
|
||||
|
||||
Bindings are a shared capability. Different products should consume it differently.
|
||||
|
||||
ACP configured bindings:
|
||||
|
||||
- compile config rules
|
||||
- resolve a target session
|
||||
- ensure the ACP session is ready through the ACP kernel
|
||||
|
||||
Codex app server:
|
||||
|
||||
- create runtime-requested bindings
|
||||
- claim inbound messages through plugin hooks
|
||||
- optionally adopt the shared stateful target contract later if it really needs long-lived session orchestration
|
||||
|
||||
Main harness:
|
||||
|
||||
- does not need to become "a binding product"
|
||||
- may eventually share small lifecycle contracts, but it should not be forced into the same engine as ACP
|
||||
|
||||
## The Key Architectural Decision
|
||||
|
||||
The shared abstraction should be:
|
||||
|
||||
- `bindings` as the capability
|
||||
- `stateful target drivers` as an optional lower-level contract
|
||||
|
||||
The shared abstraction should not be:
|
||||
|
||||
- "one runtime engine for main harness, ACP, and codex app server"
|
||||
|
||||
That would overfit very different systems into one executor.
|
||||
|
||||
## Stable Nouns
|
||||
|
||||
Core should understand only stable nouns.
|
||||
|
||||
The stable nouns are:
|
||||
|
||||
- `ConversationRef`
|
||||
- `BindingRule`
|
||||
- `CompiledBinding`
|
||||
- `BindingResolution`
|
||||
- `BindingTargetDescriptor`
|
||||
- `StatefulTargetDriver`
|
||||
- `StatefulTargetHandle`
|
||||
|
||||
ACP, codex app server, and future products should compile down to those nouns instead of leaking product-specific routing rules through core.
|
||||
|
||||
## Proposed Capability Model
|
||||
|
||||
### Binding capability
|
||||
|
||||
The binding capability should support both configured bindings and runtime-created bindings.
|
||||
|
||||
Required operations:
|
||||
|
||||
- compile configured bindings at startup or reload
|
||||
- resolve a binding from an inbound `ConversationRef`
|
||||
- create a runtime binding
|
||||
- touch and unbind an existing binding
|
||||
- dispatch a resolved binding to its target
|
||||
|
||||
### Binding target descriptor
|
||||
|
||||
A resolved binding should point to a typed target descriptor rather than ad hoc ACP- or plugin-specific metadata blobs.
|
||||
|
||||
The descriptor should be able to represent at least:
|
||||
|
||||
- plugin-owned inbound claim targets
|
||||
- stateful target drivers
|
||||
|
||||
That means the same binding capability can support both:
|
||||
|
||||
- codex app server plugin-bound conversations
|
||||
- ACP configured bindings
|
||||
|
||||
without pretending they are the same product.
|
||||
|
||||
### Stateful target driver
|
||||
|
||||
This is the reusable control-plane contract for long-lived bound targets.
|
||||
|
||||
Required operations:
|
||||
|
||||
- `ensureReady`
|
||||
- `runTurn`
|
||||
- `cancel`
|
||||
- `close`
|
||||
- `reset`
|
||||
- `status`
|
||||
- `health`
|
||||
|
||||
ACP should remain the first built-in driver.
|
||||
|
||||
If the codex app server later proves that it also needs durable session handles, it can either:
|
||||
|
||||
- use a driver that consumes this contract, or
|
||||
- keep its own product-owned runtime if that remains simpler
|
||||
|
||||
That should be a product decision, not something forced by the binding capability.
|
||||
|
||||
## Why ACP Kernel Stays In Core
|
||||
|
||||
ACP's kernel should remain in core because session lifecycle, persistence, retries, cancellation, and runtime-handle safety are generic platform machinery.
|
||||
|
||||
Those concerns are not channel-specific, and they are not codex-app-server-specific.
|
||||
|
||||
If we move that machinery into an ordinary plugin, we create circular bootstrapping:
|
||||
|
||||
- channels need it during startup and inbound routing
|
||||
- reset and recovery need it when plugins may already be degraded
|
||||
- failure semantics become special-case core logic anyway
|
||||
|
||||
If we later wrap it in a "built-in capability module", that is still effectively core.
|
||||
|
||||
## What Should Move Out Of Core
|
||||
|
||||
The following should move out of ACP-shaped core code:
|
||||
|
||||
- channel-specific configured binding matching
|
||||
- channel-specific binding target normalization
|
||||
- channel-specific recovery UX
|
||||
- ACP-specific route wrapping helpers as named ACP seams
|
||||
- codex app server fallback policy beyond generic plugin-bound dispatch behavior
|
||||
|
||||
The following should stay:
|
||||
|
||||
- generic binding storage and dispatch
|
||||
- generic ACP control plane
|
||||
- generic stateful target driver contract
|
||||
|
||||
## Current Problems To Remove
|
||||
|
||||
### Residual cleanup is now small
|
||||
|
||||
Most ACP-era compatibility names are gone from the generic seam.
|
||||
|
||||
The remaining cleanup is smaller:
|
||||
|
||||
- `src/acp/persistent-bindings.ts` compatibility barrel can be deleted once tests stop importing it
|
||||
- ACP-named tests and mocks can be renamed over time for consistency
|
||||
- docs should stop describing already-removed ACP wrappers as if they still exist
|
||||
|
||||
### Configured binding implementation is still too monolithic
|
||||
|
||||
`src/channels/plugins/configured-binding-registry.ts` still mixes:
|
||||
|
||||
- registry compilation
|
||||
- cache invalidation
|
||||
- inbound matching
|
||||
- materialization of binding targets
|
||||
- session-key reverse lookup
|
||||
|
||||
That file is now generic, but still too large and too coupled.
|
||||
|
||||
### Runtime-created plugin bindings still use a separate stack
|
||||
|
||||
`src/plugins/conversation-binding.ts` is still a separate implementation path for plugin-created bindings.
|
||||
|
||||
That means configured bindings and runtime-created bindings share storage, but not one consistent capability layer.
|
||||
|
||||
### Generic registries still hardcode ACP as a built-in
|
||||
|
||||
`src/channels/plugins/configured-binding-consumers.ts` and `src/channels/plugins/stateful-target-drivers.ts` still import ACP directly.
|
||||
|
||||
That is acceptable for now, but the clean final shape is to keep ACP built in while registering it from a dedicated bootstrap point instead of wiring it inside the generic registry files.
|
||||
|
||||
## Target Contracts
|
||||
|
||||
### Channel binding provider contract
|
||||
|
||||
Conceptually, each channel plugin should support:
|
||||
|
||||
- `compileConfiguredBinding(binding, cfg) -> CompiledBinding | null`
|
||||
- `resolveInboundConversation(event) -> ConversationRef | null`
|
||||
- `matchInboundConversation(compiledBinding, conversation) -> BindingMatch | null`
|
||||
- `describeBinding(compiledBinding) -> string | undefined`
|
||||
|
||||
### Binding capability contract
|
||||
|
||||
Core should support:
|
||||
|
||||
- `compileConfiguredBindings(cfg, plugins) -> CompiledBindingRegistry`
|
||||
- `resolveBinding(conversationRef) -> BindingResolution | null`
|
||||
- `createRuntimeBinding(target, conversationRef, metadata) -> BindingRecord`
|
||||
- `touchBinding(bindingId)`
|
||||
- `unbindBinding(bindingId | target)`
|
||||
- `dispatchResolvedBinding(bindingResolution, inboundEvent)`
|
||||
|
||||
### Stateful target driver contract
|
||||
|
||||
Core should support:
|
||||
|
||||
- `ensureReady(targetRef, cfg)`
|
||||
- `runTurn(targetRef, input)`
|
||||
- `cancel(targetRef, reason)`
|
||||
- `close(targetRef, reason)`
|
||||
- `reset(targetRef, reason)`
|
||||
- `status(targetRef)`
|
||||
- `health(targetRef)`
|
||||
|
||||
## File-Level Transition Plan
|
||||
|
||||
### Keep
|
||||
|
||||
- `src/infra/outbound/session-binding-service.ts`
|
||||
- `src/acp/control-plane/*`
|
||||
- `extensions/acpx/*`
|
||||
|
||||
### Generalize
|
||||
|
||||
- `src/plugins/conversation-binding.ts`
|
||||
- fold runtime-created plugin bindings into the same generic binding capability instead of keeping a separate implementation stack
|
||||
- `src/channels/plugins/configured-binding-registry.ts`
|
||||
- split into compiler, matcher, and session-key resolution modules with a thin facade
|
||||
- `src/channels/plugins/types.adapters.ts`
|
||||
- finish removing ACP-era aliases after the deprecation window
|
||||
- `src/plugin-sdk/conversation-runtime.ts`
|
||||
- export only the generic binding capability surfaces
|
||||
- `src/acp/persistent-bindings.lifecycle.ts`
|
||||
- either become a generic stateful target driver consumer or be renamed to ACP driver-specific lifecycle code
|
||||
|
||||
### Shrink Or Delete
|
||||
|
||||
- `src/acp/persistent-bindings.ts`
|
||||
- delete the compatibility barrel once tests import the real modules directly
|
||||
- `src/acp/persistent-bindings.resolve.ts`
|
||||
- keep only while ACP-specific compatibility helpers are still useful to internal callers
|
||||
- ACP-named test files
|
||||
- rename over time once the behavior is stable and there is no risk of mixing behavioral and naming churn
|
||||
|
||||
## Recommended Refactor Order
|
||||
|
||||
### Completed groundwork
|
||||
|
||||
The current branch has already completed most of the first migration wave:
|
||||
|
||||
- stable generic binding nouns exist
|
||||
- configured bindings compile through a generic registry
|
||||
- inbound routing goes through generic binding resolution
|
||||
- configured binding lookup no longer performs fallback plugin discovery
|
||||
- ACP is expressed as a configured-binding consumer plus a built-in stateful target driver
|
||||
|
||||
The remaining work is cleanup and unification, not first-principles redesign.
|
||||
|
||||
### Phase 1: Freeze the nouns
|
||||
|
||||
Introduce and document the stable binding and target types:
|
||||
|
||||
- `ConversationRef`
|
||||
- `CompiledBinding`
|
||||
- `BindingResolution`
|
||||
- `BindingTargetDescriptor`
|
||||
- `StatefulTargetDriver`
|
||||
|
||||
Do this before more movement so the rest of the refactor has firm vocabulary.
|
||||
|
||||
### Phase 2: Promote bindings to a first-class core capability
|
||||
|
||||
Refactor the existing generic binding store into an explicit capability layer.
|
||||
|
||||
Requirements:
|
||||
|
||||
- runtime-created bindings stay supported
|
||||
- configured bindings become first-class
|
||||
- lookup becomes channel-agnostic
|
||||
|
||||
### Phase 3: Compile configured bindings at startup and reload
|
||||
|
||||
Move configured binding compilation off the inbound hot path.
|
||||
|
||||
Requirements:
|
||||
|
||||
- load enabled channel plugins once
|
||||
- compile configured bindings once
|
||||
- rebuild on config or plugin reload
|
||||
- inbound path becomes pure registry lookup
|
||||
|
||||
### Phase 4: Expand the channel provider seam
|
||||
|
||||
Replace the ACP-specific adapter shape with a generic channel binding provider contract.
|
||||
|
||||
Requirements:
|
||||
|
||||
- channel plugins own normalization and matching
|
||||
- core no longer knows channel-specific configured binding rules
|
||||
|
||||
### Phase 5: Re-express ACP as a binding consumer plus built-in stateful target driver
|
||||
|
||||
Move ACP configured binding policy to the new binding capability while keeping ACP runtime orchestration in core.
|
||||
|
||||
Requirements:
|
||||
|
||||
- ACP configured bindings resolve through the generic binding registry
|
||||
- ACP target readiness uses the ACP driver contract
|
||||
- ACP-specific naming disappears from generic binding code
|
||||
|
||||
### Phase 6: Finish residual ACP cleanup
|
||||
|
||||
Remove the last compatibility leftovers and stale naming.
|
||||
|
||||
Requirements:
|
||||
|
||||
- delete `src/acp/persistent-bindings.ts`
|
||||
- rename ACP-named tests where that improves clarity without changing behavior
|
||||
- keep docs synchronized with the actual generic seam instead of the earlier transition state
|
||||
|
||||
### Phase 7: Split the configured binding registry by responsibility
|
||||
|
||||
Refactor `src/channels/plugins/configured-binding-registry.ts` into smaller modules.
|
||||
|
||||
Suggested split:
|
||||
|
||||
- compiler module
|
||||
- inbound matcher module
|
||||
- session-key reverse lookup module
|
||||
- thin public facade
|
||||
|
||||
Requirements:
|
||||
|
||||
- caching behavior remains unchanged
|
||||
- matching behavior remains unchanged
|
||||
- session-key resolution behavior remains unchanged
|
||||
|
||||
### Phase 8: Keep codex app server on the same binding capability
|
||||
|
||||
Do not force the codex app server into ACP semantics.
|
||||
|
||||
Requirements:
|
||||
|
||||
- codex app server keeps runtime-created bindings through the same binding capability
|
||||
- inbound claim remains the default delivery path
|
||||
- only adopt the stateful target driver seam if the app server truly needs long-lived target orchestration
|
||||
- `src/plugins/conversation-binding.ts` stops being a separate binding stack and becomes a consumer of the generic binding capability
|
||||
|
||||
### Phase 9: Decouple built-in ACP registration from generic registry files
|
||||
|
||||
Keep ACP built in, but stop importing it directly from the generic registry modules.
|
||||
|
||||
Requirements:
|
||||
|
||||
- `src/channels/plugins/configured-binding-consumers.ts` no longer hardcodes ACP imports
|
||||
- `src/channels/plugins/stateful-target-drivers.ts` no longer hardcodes ACP imports
|
||||
- ACP still registers by default during normal startup
|
||||
- generic registry files remain product-agnostic
|
||||
|
||||
### Phase 10: Remove ACP-shaped compatibility facades
|
||||
|
||||
Once all call sites are on the generic capability:
|
||||
|
||||
- delete ACP-shaped routing helpers
|
||||
- delete hot-path plugin bootstrapping logic
|
||||
- keep only thin compatibility exports if external plugins still need a deprecation window
|
||||
|
||||
## Success Criteria
|
||||
|
||||
The architecture is done when all of these are true:
|
||||
|
||||
- no inbound configured-binding resolution performs plugin discovery
|
||||
- no channel-specific binding semantics remain in generic core binding code
|
||||
- ACP still uses a core session kernel
|
||||
- codex app server and ACP both sit on top of the same binding capability
|
||||
- the binding capability can represent both configured and runtime-created bindings
|
||||
- runtime-created plugin bindings do not use a separate implementation stack
|
||||
- long-lived target orchestration is shared through a small core driver contract
|
||||
- generic registry files do not import ACP directly
|
||||
- ACP-era alias names are gone from the generic/plugin SDK surface
|
||||
- the main harness is not forced into the ACP engine
|
||||
- external plugins can use the same capability without internal imports
|
||||
|
||||
## Non-Goals
|
||||
|
||||
These are not goals of the remaining refactor:
|
||||
|
||||
- moving the ACP session kernel into an ordinary plugin
|
||||
- forcing the main harness, ACP, and codex app server into one executor
|
||||
- making every channel implement its own retry and session-safety logic
|
||||
- keeping ACP-shaped naming in the long-term generic binding layer
|
||||
|
||||
## Bottom Line
|
||||
|
||||
The right 20-year split is:
|
||||
|
||||
- bindings are the shared core capability
|
||||
- ACP session orchestration remains a small built-in core kernel
|
||||
- channel plugins own binding semantics
|
||||
- backend plugins own runtime protocol details
|
||||
- product consumers like ACP configured bindings and codex app server build on the same binding capability without being forced into one runtime engine
|
||||
|
||||
That is the leanest core that still has honest boundaries.
|
||||
@ -0,0 +1,100 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { importFreshModule } from "../../test/helpers/import-fresh.js";
|
||||
import type { OpenClawConfig } from "../config/config.js";
|
||||
|
||||
const managerMocks = vi.hoisted(() => ({
|
||||
closeSession: vi.fn(),
|
||||
initializeSession: vi.fn(),
|
||||
updateSessionRuntimeOptions: vi.fn(),
|
||||
}));
|
||||
|
||||
const sessionMetaMocks = vi.hoisted(() => ({
|
||||
readAcpSessionEntry: vi.fn(),
|
||||
}));
|
||||
|
||||
const resolveMocks = vi.hoisted(() => ({
|
||||
resolveConfiguredAcpBindingSpecBySessionKey: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("./control-plane/manager.js", () => ({
|
||||
getAcpSessionManager: () => ({
|
||||
closeSession: managerMocks.closeSession,
|
||||
initializeSession: managerMocks.initializeSession,
|
||||
updateSessionRuntimeOptions: managerMocks.updateSessionRuntimeOptions,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("./runtime/session-meta.js", () => ({
|
||||
readAcpSessionEntry: sessionMetaMocks.readAcpSessionEntry,
|
||||
}));
|
||||
|
||||
vi.mock("./persistent-bindings.resolve.js", () => ({
|
||||
resolveConfiguredAcpBindingSpecBySessionKey:
|
||||
resolveMocks.resolveConfiguredAcpBindingSpecBySessionKey,
|
||||
}));
|
||||
type BindingTargetsModule = typeof import("../channels/plugins/binding-targets.js");
|
||||
let bindingTargets: BindingTargetsModule;
|
||||
let bindingTargetsImportScope = 0;
|
||||
|
||||
const baseCfg = {
|
||||
session: { mainKey: "main", scope: "per-sender" },
|
||||
agents: {
|
||||
list: [{ id: "codex" }, { id: "claude" }],
|
||||
},
|
||||
} satisfies OpenClawConfig;
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.resetModules();
|
||||
bindingTargetsImportScope += 1;
|
||||
bindingTargets = await importFreshModule<BindingTargetsModule>(
|
||||
import.meta.url,
|
||||
`../channels/plugins/binding-targets.js?scope=${bindingTargetsImportScope}`,
|
||||
);
|
||||
managerMocks.closeSession.mockReset().mockResolvedValue({
|
||||
runtimeClosed: true,
|
||||
metaCleared: false,
|
||||
});
|
||||
managerMocks.initializeSession.mockReset().mockResolvedValue(undefined);
|
||||
managerMocks.updateSessionRuntimeOptions.mockReset().mockResolvedValue(undefined);
|
||||
sessionMetaMocks.readAcpSessionEntry.mockReset().mockReturnValue(undefined);
|
||||
resolveMocks.resolveConfiguredAcpBindingSpecBySessionKey.mockReset().mockReturnValue(null);
|
||||
});
|
||||
|
||||
describe("resetConfiguredBindingTargetInPlace", () => {
|
||||
it("does not resolve configured bindings when ACP metadata already exists", async () => {
|
||||
const sessionKey = "agent:claude:acp:binding:discord:default:9373ab192b2317f4";
|
||||
sessionMetaMocks.readAcpSessionEntry.mockReturnValue({
|
||||
acp: {
|
||||
agent: "claude",
|
||||
mode: "persistent",
|
||||
backend: "acpx",
|
||||
runtimeOptions: { cwd: "/home/bob/clawd" },
|
||||
},
|
||||
});
|
||||
resolveMocks.resolveConfiguredAcpBindingSpecBySessionKey.mockImplementation(() => {
|
||||
throw new Error("configured binding resolution should be skipped");
|
||||
});
|
||||
|
||||
const result = await bindingTargets.resetConfiguredBindingTargetInPlace({
|
||||
cfg: baseCfg,
|
||||
sessionKey,
|
||||
reason: "reset",
|
||||
});
|
||||
|
||||
expect(result).toEqual({ ok: true });
|
||||
expect(resolveMocks.resolveConfiguredAcpBindingSpecBySessionKey).not.toHaveBeenCalled();
|
||||
expect(managerMocks.closeSession).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
sessionKey,
|
||||
clearMeta: false,
|
||||
}),
|
||||
);
|
||||
expect(managerMocks.initializeSession).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
sessionKey,
|
||||
agent: "claude",
|
||||
backendId: "acpx",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@ -1,312 +1,40 @@
|
||||
import { getChannelPlugin } from "../channels/plugins/index.js";
|
||||
import { listAcpBindings } from "../config/bindings.js";
|
||||
import type { OpenClawConfig } from "../config/config.js";
|
||||
import type { AgentAcpBinding } from "../config/types.js";
|
||||
import { pickFirstExistingAgentId } from "../routing/resolve-route.js";
|
||||
import {
|
||||
DEFAULT_ACCOUNT_ID,
|
||||
normalizeAccountId,
|
||||
parseAgentSessionKey,
|
||||
} from "../routing/session-key.js";
|
||||
resolveConfiguredBindingRecord,
|
||||
resolveConfiguredBindingRecordBySessionKey,
|
||||
resolveConfiguredBindingRecordForConversation,
|
||||
} from "../channels/plugins/binding-registry.js";
|
||||
import type { OpenClawConfig } from "../config/config.js";
|
||||
import type { ConversationRef } from "../infra/outbound/session-binding-service.js";
|
||||
import {
|
||||
buildConfiguredAcpSessionKey,
|
||||
normalizeBindingConfig,
|
||||
normalizeMode,
|
||||
normalizeText,
|
||||
toConfiguredAcpBindingRecord,
|
||||
type ConfiguredAcpBindingChannel,
|
||||
resolveConfiguredAcpBindingSpecFromRecord,
|
||||
toResolvedConfiguredAcpBinding,
|
||||
type ConfiguredAcpBindingSpec,
|
||||
type ResolvedConfiguredAcpBinding,
|
||||
} from "./persistent-bindings.types.js";
|
||||
|
||||
function normalizeBindingChannel(value: string | undefined): ConfiguredAcpBindingChannel | null {
|
||||
const normalized = (value ?? "").trim().toLowerCase();
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
const plugin = getChannelPlugin(normalized);
|
||||
return plugin?.acpBindings ? plugin.id : null;
|
||||
}
|
||||
|
||||
function resolveAccountMatchPriority(match: string | undefined, actual: string): 0 | 1 | 2 {
|
||||
const trimmed = (match ?? "").trim();
|
||||
if (!trimmed) {
|
||||
return actual === DEFAULT_ACCOUNT_ID ? 2 : 0;
|
||||
}
|
||||
if (trimmed === "*") {
|
||||
return 1;
|
||||
}
|
||||
return normalizeAccountId(trimmed) === actual ? 2 : 0;
|
||||
}
|
||||
|
||||
function resolveBindingConversationId(binding: AgentAcpBinding): string | null {
|
||||
const id = binding.match.peer?.id?.trim();
|
||||
return id ? id : null;
|
||||
}
|
||||
|
||||
function parseConfiguredBindingSessionKey(params: {
|
||||
sessionKey: string;
|
||||
}): { channel: ConfiguredAcpBindingChannel; accountId: string } | null {
|
||||
const parsed = parseAgentSessionKey(params.sessionKey);
|
||||
const rest = parsed?.rest?.trim().toLowerCase() ?? "";
|
||||
if (!rest) {
|
||||
return null;
|
||||
}
|
||||
const tokens = rest.split(":");
|
||||
if (tokens.length !== 5 || tokens[0] !== "acp" || tokens[1] !== "binding") {
|
||||
return null;
|
||||
}
|
||||
const channel = normalizeBindingChannel(tokens[2]);
|
||||
if (!channel) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
channel,
|
||||
accountId: normalizeAccountId(tokens[3]),
|
||||
};
|
||||
}
|
||||
|
||||
function resolveAgentRuntimeAcpDefaults(params: { cfg: OpenClawConfig; ownerAgentId: string }): {
|
||||
acpAgentId?: string;
|
||||
mode?: string;
|
||||
cwd?: string;
|
||||
backend?: string;
|
||||
} {
|
||||
const agent = params.cfg.agents?.list?.find(
|
||||
(entry) => entry.id?.trim().toLowerCase() === params.ownerAgentId.toLowerCase(),
|
||||
);
|
||||
if (!agent || agent.runtime?.type !== "acp") {
|
||||
return {};
|
||||
}
|
||||
return {
|
||||
acpAgentId: normalizeText(agent.runtime.acp?.agent),
|
||||
mode: normalizeText(agent.runtime.acp?.mode),
|
||||
cwd: normalizeText(agent.runtime.acp?.cwd),
|
||||
backend: normalizeText(agent.runtime.acp?.backend),
|
||||
};
|
||||
}
|
||||
|
||||
function toConfiguredBindingSpec(params: {
|
||||
export function resolveConfiguredAcpBindingRecord(params: {
|
||||
cfg: OpenClawConfig;
|
||||
channel: ConfiguredAcpBindingChannel;
|
||||
channel: string;
|
||||
accountId: string;
|
||||
conversationId: string;
|
||||
parentConversationId?: string;
|
||||
binding: AgentAcpBinding;
|
||||
}): ConfiguredAcpBindingSpec {
|
||||
const accountId = normalizeAccountId(params.accountId);
|
||||
const agentId = pickFirstExistingAgentId(params.cfg, params.binding.agentId ?? "main");
|
||||
const runtimeDefaults = resolveAgentRuntimeAcpDefaults({
|
||||
cfg: params.cfg,
|
||||
ownerAgentId: agentId,
|
||||
});
|
||||
const bindingOverrides = normalizeBindingConfig(params.binding.acp);
|
||||
const acpAgentId = normalizeText(runtimeDefaults.acpAgentId);
|
||||
const mode = normalizeMode(bindingOverrides.mode ?? runtimeDefaults.mode);
|
||||
return {
|
||||
channel: params.channel,
|
||||
accountId,
|
||||
conversationId: params.conversationId,
|
||||
parentConversationId: params.parentConversationId,
|
||||
agentId,
|
||||
acpAgentId,
|
||||
mode,
|
||||
cwd: bindingOverrides.cwd ?? runtimeDefaults.cwd,
|
||||
backend: bindingOverrides.backend ?? runtimeDefaults.backend,
|
||||
label: bindingOverrides.label,
|
||||
};
|
||||
}): ResolvedConfiguredAcpBinding | null {
|
||||
const resolved = resolveConfiguredBindingRecord(params);
|
||||
return resolved ? toResolvedConfiguredAcpBinding(resolved.record) : null;
|
||||
}
|
||||
|
||||
function resolveConfiguredBindingRecord(params: {
|
||||
export function resolveConfiguredAcpBindingRecordForConversation(params: {
|
||||
cfg: OpenClawConfig;
|
||||
bindings: AgentAcpBinding[];
|
||||
channel: ConfiguredAcpBindingChannel;
|
||||
accountId: string;
|
||||
selectConversation: (binding: AgentAcpBinding) => {
|
||||
conversationId: string;
|
||||
parentConversationId?: string;
|
||||
matchPriority?: number;
|
||||
} | null;
|
||||
conversation: ConversationRef;
|
||||
}): ResolvedConfiguredAcpBinding | null {
|
||||
let wildcardMatch: {
|
||||
binding: AgentAcpBinding;
|
||||
conversationId: string;
|
||||
parentConversationId?: string;
|
||||
matchPriority: number;
|
||||
} | null = null;
|
||||
let exactMatch: {
|
||||
binding: AgentAcpBinding;
|
||||
conversationId: string;
|
||||
parentConversationId?: string;
|
||||
matchPriority: number;
|
||||
} | null = null;
|
||||
for (const binding of params.bindings) {
|
||||
if (normalizeBindingChannel(binding.match.channel) !== params.channel) {
|
||||
continue;
|
||||
}
|
||||
const accountMatchPriority = resolveAccountMatchPriority(
|
||||
binding.match.accountId,
|
||||
params.accountId,
|
||||
);
|
||||
if (accountMatchPriority === 0) {
|
||||
continue;
|
||||
}
|
||||
const conversation = params.selectConversation(binding);
|
||||
if (!conversation) {
|
||||
continue;
|
||||
}
|
||||
const matchPriority = conversation.matchPriority ?? 0;
|
||||
if (accountMatchPriority === 2) {
|
||||
if (!exactMatch || matchPriority > exactMatch.matchPriority) {
|
||||
exactMatch = {
|
||||
binding,
|
||||
conversationId: conversation.conversationId,
|
||||
parentConversationId: conversation.parentConversationId,
|
||||
matchPriority,
|
||||
};
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!wildcardMatch || matchPriority > wildcardMatch.matchPriority) {
|
||||
wildcardMatch = {
|
||||
binding,
|
||||
conversationId: conversation.conversationId,
|
||||
parentConversationId: conversation.parentConversationId,
|
||||
matchPriority,
|
||||
};
|
||||
}
|
||||
}
|
||||
if (exactMatch) {
|
||||
const spec = toConfiguredBindingSpec({
|
||||
cfg: params.cfg,
|
||||
channel: params.channel,
|
||||
accountId: params.accountId,
|
||||
conversationId: exactMatch.conversationId,
|
||||
parentConversationId: exactMatch.parentConversationId,
|
||||
binding: exactMatch.binding,
|
||||
});
|
||||
return {
|
||||
spec,
|
||||
record: toConfiguredAcpBindingRecord(spec),
|
||||
};
|
||||
}
|
||||
if (!wildcardMatch) {
|
||||
return null;
|
||||
}
|
||||
const spec = toConfiguredBindingSpec({
|
||||
cfg: params.cfg,
|
||||
channel: params.channel,
|
||||
accountId: params.accountId,
|
||||
conversationId: wildcardMatch.conversationId,
|
||||
parentConversationId: wildcardMatch.parentConversationId,
|
||||
binding: wildcardMatch.binding,
|
||||
});
|
||||
return {
|
||||
spec,
|
||||
record: toConfiguredAcpBindingRecord(spec),
|
||||
};
|
||||
const resolved = resolveConfiguredBindingRecordForConversation(params);
|
||||
return resolved ? toResolvedConfiguredAcpBinding(resolved.record) : null;
|
||||
}
|
||||
|
||||
export function resolveConfiguredAcpBindingSpecBySessionKey(params: {
|
||||
cfg: OpenClawConfig;
|
||||
sessionKey: string;
|
||||
}): ConfiguredAcpBindingSpec | null {
|
||||
const sessionKey = params.sessionKey.trim();
|
||||
if (!sessionKey) {
|
||||
return null;
|
||||
}
|
||||
const parsedSessionKey = parseConfiguredBindingSessionKey({ sessionKey });
|
||||
if (!parsedSessionKey) {
|
||||
return null;
|
||||
}
|
||||
const plugin = getChannelPlugin(parsedSessionKey.channel);
|
||||
const acpBindings = plugin?.acpBindings;
|
||||
if (!acpBindings?.normalizeConfiguredBindingTarget) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let wildcardMatch: ConfiguredAcpBindingSpec | null = null;
|
||||
for (const binding of listAcpBindings(params.cfg)) {
|
||||
const channel = normalizeBindingChannel(binding.match.channel);
|
||||
if (!channel || channel !== parsedSessionKey.channel) {
|
||||
continue;
|
||||
}
|
||||
const accountMatchPriority = resolveAccountMatchPriority(
|
||||
binding.match.accountId,
|
||||
parsedSessionKey.accountId,
|
||||
);
|
||||
if (accountMatchPriority === 0) {
|
||||
continue;
|
||||
}
|
||||
const targetConversationId = resolveBindingConversationId(binding);
|
||||
if (!targetConversationId) {
|
||||
continue;
|
||||
}
|
||||
const target = acpBindings.normalizeConfiguredBindingTarget({
|
||||
binding,
|
||||
conversationId: targetConversationId,
|
||||
});
|
||||
if (!target) {
|
||||
continue;
|
||||
}
|
||||
const spec = toConfiguredBindingSpec({
|
||||
cfg: params.cfg,
|
||||
channel,
|
||||
accountId: parsedSessionKey.accountId,
|
||||
conversationId: target.conversationId,
|
||||
parentConversationId: target.parentConversationId,
|
||||
binding,
|
||||
});
|
||||
if (buildConfiguredAcpSessionKey(spec) !== sessionKey) {
|
||||
continue;
|
||||
}
|
||||
if (accountMatchPriority === 2) {
|
||||
return spec;
|
||||
}
|
||||
if (!wildcardMatch) {
|
||||
wildcardMatch = spec;
|
||||
}
|
||||
}
|
||||
return wildcardMatch;
|
||||
}
|
||||
|
||||
export function resolveConfiguredAcpBindingRecord(params: {
|
||||
cfg: OpenClawConfig;
|
||||
channel: string;
|
||||
accountId: string;
|
||||
conversationId: string;
|
||||
parentConversationId?: string;
|
||||
}): ResolvedConfiguredAcpBinding | null {
|
||||
const channel = normalizeBindingChannel(params.channel);
|
||||
const accountId = normalizeAccountId(params.accountId);
|
||||
const conversationId = params.conversationId.trim();
|
||||
const parentConversationId = params.parentConversationId?.trim() || undefined;
|
||||
if (!channel || !conversationId) {
|
||||
return null;
|
||||
}
|
||||
const plugin = getChannelPlugin(channel);
|
||||
const acpBindings = plugin?.acpBindings;
|
||||
if (!acpBindings?.matchConfiguredBinding) {
|
||||
return null;
|
||||
}
|
||||
const matchConfiguredBinding = acpBindings.matchConfiguredBinding;
|
||||
|
||||
return resolveConfiguredBindingRecord({
|
||||
cfg: params.cfg,
|
||||
bindings: listAcpBindings(params.cfg),
|
||||
channel,
|
||||
accountId,
|
||||
selectConversation: (binding) => {
|
||||
const bindingConversationId = resolveBindingConversationId(binding);
|
||||
if (!bindingConversationId) {
|
||||
return null;
|
||||
}
|
||||
return matchConfiguredBinding({
|
||||
binding,
|
||||
bindingConversationId,
|
||||
conversationId,
|
||||
parentConversationId,
|
||||
});
|
||||
},
|
||||
});
|
||||
const resolved = resolveConfiguredBindingRecordBySessionKey(params);
|
||||
return resolved ? resolveConfiguredAcpBindingSpecFromRecord(resolved.record) : null;
|
||||
}
|
||||
|
||||
@ -1,81 +0,0 @@
|
||||
import type { OpenClawConfig } from "../config/config.js";
|
||||
import type { ResolvedAgentRoute } from "../routing/resolve-route.js";
|
||||
import { deriveLastRoutePolicy } from "../routing/resolve-route.js";
|
||||
import { resolveAgentIdFromSessionKey } from "../routing/session-key.js";
|
||||
import {
|
||||
ensureConfiguredAcpBindingSession,
|
||||
resolveConfiguredAcpBindingRecord,
|
||||
type ConfiguredAcpBindingChannel,
|
||||
type ResolvedConfiguredAcpBinding,
|
||||
} from "./persistent-bindings.js";
|
||||
|
||||
export function resolveConfiguredAcpRoute(params: {
|
||||
cfg: OpenClawConfig;
|
||||
route: ResolvedAgentRoute;
|
||||
channel: ConfiguredAcpBindingChannel;
|
||||
accountId: string;
|
||||
conversationId: string;
|
||||
parentConversationId?: string;
|
||||
}): {
|
||||
configuredBinding: ResolvedConfiguredAcpBinding | null;
|
||||
route: ResolvedAgentRoute;
|
||||
boundSessionKey?: string;
|
||||
boundAgentId?: string;
|
||||
} {
|
||||
const configuredBinding = resolveConfiguredAcpBindingRecord({
|
||||
cfg: params.cfg,
|
||||
channel: params.channel,
|
||||
accountId: params.accountId,
|
||||
conversationId: params.conversationId,
|
||||
parentConversationId: params.parentConversationId,
|
||||
});
|
||||
if (!configuredBinding) {
|
||||
return {
|
||||
configuredBinding: null,
|
||||
route: params.route,
|
||||
};
|
||||
}
|
||||
const boundSessionKey = configuredBinding.record.targetSessionKey?.trim() ?? "";
|
||||
if (!boundSessionKey) {
|
||||
return {
|
||||
configuredBinding,
|
||||
route: params.route,
|
||||
};
|
||||
}
|
||||
const boundAgentId = resolveAgentIdFromSessionKey(boundSessionKey) || params.route.agentId;
|
||||
return {
|
||||
configuredBinding,
|
||||
boundSessionKey,
|
||||
boundAgentId,
|
||||
route: {
|
||||
...params.route,
|
||||
sessionKey: boundSessionKey,
|
||||
agentId: boundAgentId,
|
||||
lastRoutePolicy: deriveLastRoutePolicy({
|
||||
sessionKey: boundSessionKey,
|
||||
mainSessionKey: params.route.mainSessionKey,
|
||||
}),
|
||||
matchedBy: "binding.channel",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function ensureConfiguredAcpRouteReady(params: {
|
||||
cfg: OpenClawConfig;
|
||||
configuredBinding: ResolvedConfiguredAcpBinding | null;
|
||||
}): Promise<{ ok: true } | { ok: false; error: string }> {
|
||||
if (!params.configuredBinding) {
|
||||
return { ok: true };
|
||||
}
|
||||
const ensured = await ensureConfiguredAcpBindingSession({
|
||||
cfg: params.cfg,
|
||||
spec: params.configuredBinding.spec,
|
||||
});
|
||||
if (ensured.ok) {
|
||||
return { ok: true };
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
error: ensured.error ?? "unknown error",
|
||||
};
|
||||
}
|
||||
@ -1,19 +0,0 @@
|
||||
export {
|
||||
buildConfiguredAcpSessionKey,
|
||||
normalizeBindingConfig,
|
||||
normalizeMode,
|
||||
normalizeText,
|
||||
toConfiguredAcpBindingRecord,
|
||||
type AcpBindingConfigShape,
|
||||
type ConfiguredAcpBindingChannel,
|
||||
type ConfiguredAcpBindingSpec,
|
||||
type ResolvedConfiguredAcpBinding,
|
||||
} from "./persistent-bindings.types.js";
|
||||
export {
|
||||
ensureConfiguredAcpBindingSession,
|
||||
resetAcpSessionInPlace,
|
||||
} from "./persistent-bindings.lifecycle.js";
|
||||
export {
|
||||
resolveConfiguredAcpBindingRecord,
|
||||
resolveConfiguredAcpBindingSpecBySessionKey,
|
||||
} from "./persistent-bindings.resolve.js";
|
||||
@ -0,0 +1,48 @@
|
||||
import {
|
||||
getSessionBindingService,
|
||||
type ConversationRef,
|
||||
type SessionBindingBindInput,
|
||||
type SessionBindingCapabilities,
|
||||
type SessionBindingRecord,
|
||||
type SessionBindingUnbindInput,
|
||||
} from "../infra/outbound/session-binding-service.js";
|
||||
|
||||
// Shared binding record helpers used by both configured bindings and
|
||||
// runtime-created plugin conversation bindings.
|
||||
export async function createConversationBindingRecord(
|
||||
input: SessionBindingBindInput,
|
||||
): Promise<SessionBindingRecord> {
|
||||
return await getSessionBindingService().bind(input);
|
||||
}
|
||||
|
||||
export function getConversationBindingCapabilities(params: {
|
||||
channel: string;
|
||||
accountId: string;
|
||||
}): SessionBindingCapabilities {
|
||||
return getSessionBindingService().getCapabilities(params);
|
||||
}
|
||||
|
||||
export function listSessionBindingRecords(targetSessionKey: string): SessionBindingRecord[] {
|
||||
return getSessionBindingService().listBySession(targetSessionKey);
|
||||
}
|
||||
|
||||
export function resolveConversationBindingRecord(
|
||||
conversation: ConversationRef,
|
||||
): SessionBindingRecord | null {
|
||||
return getSessionBindingService().resolveByConversation(conversation);
|
||||
}
|
||||
|
||||
export function touchConversationBindingRecord(bindingId: string, at?: number): void {
|
||||
const service = getSessionBindingService();
|
||||
if (typeof at === "number") {
|
||||
service.touch(bindingId, at);
|
||||
return;
|
||||
}
|
||||
service.touch(bindingId);
|
||||
}
|
||||
|
||||
export async function unbindConversationBindingRecord(
|
||||
input: SessionBindingUnbindInput,
|
||||
): Promise<SessionBindingRecord[]> {
|
||||
return await getSessionBindingService().unbind(input);
|
||||
}
|
||||
@ -0,0 +1,252 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { buildConfiguredAcpSessionKey } from "../../acp/persistent-bindings.types.js";
|
||||
|
||||
const resolveAgentConfigMock = vi.hoisted(() => vi.fn());
|
||||
const resolveDefaultAgentIdMock = vi.hoisted(() => vi.fn());
|
||||
const resolveAgentWorkspaceDirMock = vi.hoisted(() => vi.fn());
|
||||
const getChannelPluginMock = vi.hoisted(() => vi.fn());
|
||||
const getActivePluginRegistryMock = vi.hoisted(() => vi.fn());
|
||||
const getActivePluginRegistryVersionMock = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock("../../agents/agent-scope.js", () => ({
|
||||
resolveAgentConfig: (...args: unknown[]) => resolveAgentConfigMock(...args),
|
||||
resolveDefaultAgentId: (...args: unknown[]) => resolveDefaultAgentIdMock(...args),
|
||||
resolveAgentWorkspaceDir: (...args: unknown[]) => resolveAgentWorkspaceDirMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock("./index.js", () => ({
|
||||
getChannelPlugin: (...args: unknown[]) => getChannelPluginMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../../plugins/runtime.js", () => ({
|
||||
getActivePluginRegistry: (...args: unknown[]) => getActivePluginRegistryMock(...args),
|
||||
getActivePluginRegistryVersion: (...args: unknown[]) =>
|
||||
getActivePluginRegistryVersionMock(...args),
|
||||
}));
|
||||
|
||||
async function importConfiguredBindings() {
|
||||
const builtins = await import("./configured-binding-builtins.js");
|
||||
builtins.ensureConfiguredBindingBuiltinsRegistered();
|
||||
return await import("./configured-binding-registry.js");
|
||||
}
|
||||
|
||||
function createConfig(options?: { bindingAgentId?: string; accountId?: string }) {
|
||||
return {
|
||||
agents: {
|
||||
list: [{ id: "main" }, { id: "codex" }],
|
||||
},
|
||||
bindings: [
|
||||
{
|
||||
type: "acp",
|
||||
agentId: options?.bindingAgentId ?? "codex",
|
||||
match: {
|
||||
channel: "discord",
|
||||
accountId: options?.accountId ?? "default",
|
||||
peer: {
|
||||
kind: "channel",
|
||||
id: "1479098716916023408",
|
||||
},
|
||||
},
|
||||
acp: {
|
||||
backend: "acpx",
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function createDiscordAcpPlugin(overrides?: {
|
||||
compileConfiguredBinding?: ReturnType<typeof vi.fn>;
|
||||
matchInboundConversation?: ReturnType<typeof vi.fn>;
|
||||
}) {
|
||||
const compileConfiguredBinding =
|
||||
overrides?.compileConfiguredBinding ??
|
||||
vi.fn(({ conversationId }: { conversationId: string }) => ({
|
||||
conversationId,
|
||||
}));
|
||||
const matchInboundConversation =
|
||||
overrides?.matchInboundConversation ??
|
||||
vi.fn(
|
||||
({
|
||||
compiledBinding,
|
||||
conversationId,
|
||||
parentConversationId,
|
||||
}: {
|
||||
compiledBinding: { conversationId: string };
|
||||
conversationId: string;
|
||||
parentConversationId?: string;
|
||||
}) => {
|
||||
if (compiledBinding.conversationId === conversationId) {
|
||||
return { conversationId, matchPriority: 2 };
|
||||
}
|
||||
if (parentConversationId && compiledBinding.conversationId === parentConversationId) {
|
||||
return { conversationId: parentConversationId, matchPriority: 1 };
|
||||
}
|
||||
return null;
|
||||
},
|
||||
);
|
||||
return {
|
||||
id: "discord",
|
||||
bindings: {
|
||||
compileConfiguredBinding,
|
||||
matchInboundConversation,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("configured binding registry", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
resolveAgentConfigMock.mockReset().mockReturnValue(undefined);
|
||||
resolveDefaultAgentIdMock.mockReset().mockReturnValue("main");
|
||||
resolveAgentWorkspaceDirMock.mockReset().mockReturnValue("/tmp/workspace");
|
||||
getChannelPluginMock.mockReset();
|
||||
getActivePluginRegistryMock.mockReset().mockReturnValue({ channels: [] });
|
||||
getActivePluginRegistryVersionMock.mockReset().mockReturnValue(1);
|
||||
});
|
||||
|
||||
it("resolves configured ACP bindings from an already loaded channel plugin", async () => {
|
||||
const plugin = createDiscordAcpPlugin();
|
||||
getChannelPluginMock.mockReturnValue(plugin);
|
||||
const bindingRegistry = await importConfiguredBindings();
|
||||
|
||||
const resolved = bindingRegistry.resolveConfiguredBindingRecord({
|
||||
cfg: createConfig() as never,
|
||||
channel: "discord",
|
||||
accountId: "default",
|
||||
conversationId: "1479098716916023408",
|
||||
});
|
||||
|
||||
expect(resolved?.record.conversation.channel).toBe("discord");
|
||||
expect(resolved?.record.metadata?.backend).toBe("acpx");
|
||||
expect(plugin.bindings?.compileConfiguredBinding).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("resolves configured ACP bindings from canonical conversation refs", async () => {
|
||||
const plugin = createDiscordAcpPlugin();
|
||||
getChannelPluginMock.mockReturnValue(plugin);
|
||||
const bindingRegistry = await importConfiguredBindings();
|
||||
|
||||
const resolved = bindingRegistry.resolveConfiguredBinding({
|
||||
cfg: createConfig() as never,
|
||||
conversation: {
|
||||
channel: "discord",
|
||||
accountId: "default",
|
||||
conversationId: "1479098716916023408",
|
||||
},
|
||||
});
|
||||
|
||||
expect(resolved?.conversation).toEqual({
|
||||
channel: "discord",
|
||||
accountId: "default",
|
||||
conversationId: "1479098716916023408",
|
||||
});
|
||||
expect(resolved?.record.conversation.channel).toBe("discord");
|
||||
expect(resolved?.statefulTarget).toEqual({
|
||||
kind: "stateful",
|
||||
driverId: "acp",
|
||||
sessionKey: resolved?.record.targetSessionKey,
|
||||
agentId: "codex",
|
||||
label: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it("primes compiled ACP bindings from the already loaded active registry once", async () => {
|
||||
const plugin = createDiscordAcpPlugin();
|
||||
const cfg = createConfig({ bindingAgentId: "codex" });
|
||||
getChannelPluginMock.mockReturnValue(undefined);
|
||||
getActivePluginRegistryMock.mockReturnValue({
|
||||
channels: [{ plugin }],
|
||||
});
|
||||
const bindingRegistry = await importConfiguredBindings();
|
||||
|
||||
const primed = bindingRegistry.primeConfiguredBindingRegistry({
|
||||
cfg: cfg as never,
|
||||
});
|
||||
const resolved = bindingRegistry.resolveConfiguredBindingRecord({
|
||||
cfg: cfg as never,
|
||||
channel: "discord",
|
||||
accountId: "default",
|
||||
conversationId: "1479098716916023408",
|
||||
});
|
||||
|
||||
expect(primed).toEqual({ bindingCount: 1, channelCount: 1 });
|
||||
expect(resolved?.statefulTarget.agentId).toBe("codex");
|
||||
expect(plugin.bindings?.compileConfiguredBinding).toHaveBeenCalledTimes(1);
|
||||
|
||||
const second = bindingRegistry.resolveConfiguredBindingRecord({
|
||||
cfg: cfg as never,
|
||||
channel: "discord",
|
||||
accountId: "default",
|
||||
conversationId: "1479098716916023408",
|
||||
});
|
||||
|
||||
expect(second?.statefulTarget.agentId).toBe("codex");
|
||||
});
|
||||
|
||||
it("resolves wildcard binding session keys from the compiled registry", async () => {
|
||||
const plugin = createDiscordAcpPlugin();
|
||||
getChannelPluginMock.mockReturnValue(plugin);
|
||||
const bindingRegistry = await importConfiguredBindings();
|
||||
|
||||
const resolved = bindingRegistry.resolveConfiguredBindingRecordBySessionKey({
|
||||
cfg: createConfig({ accountId: "*" }) as never,
|
||||
sessionKey: buildConfiguredAcpSessionKey({
|
||||
channel: "discord",
|
||||
accountId: "work",
|
||||
conversationId: "1479098716916023408",
|
||||
agentId: "codex",
|
||||
mode: "persistent",
|
||||
backend: "acpx",
|
||||
}),
|
||||
});
|
||||
|
||||
expect(resolved?.record.conversation.channel).toBe("discord");
|
||||
expect(resolved?.record.conversation.accountId).toBe("work");
|
||||
expect(resolved?.record.metadata?.backend).toBe("acpx");
|
||||
});
|
||||
|
||||
it("does not perform late plugin discovery when a channel plugin is unavailable", async () => {
|
||||
const bindingRegistry = await importConfiguredBindings();
|
||||
|
||||
const resolved = bindingRegistry.resolveConfiguredBindingRecord({
|
||||
cfg: createConfig() as never,
|
||||
channel: "discord",
|
||||
accountId: "default",
|
||||
conversationId: "1479098716916023408",
|
||||
});
|
||||
|
||||
expect(resolved).toBeNull();
|
||||
});
|
||||
|
||||
it("rebuilds the compiled registry when the active plugin registry version changes", async () => {
|
||||
const plugin = createDiscordAcpPlugin();
|
||||
getChannelPluginMock.mockReturnValue(plugin);
|
||||
getActivePluginRegistryVersionMock.mockReturnValue(10);
|
||||
const cfg = createConfig();
|
||||
const bindingRegistry = await importConfiguredBindings();
|
||||
|
||||
bindingRegistry.resolveConfiguredBindingRecord({
|
||||
cfg: cfg as never,
|
||||
channel: "discord",
|
||||
accountId: "default",
|
||||
conversationId: "1479098716916023408",
|
||||
});
|
||||
bindingRegistry.resolveConfiguredBindingRecord({
|
||||
cfg: cfg as never,
|
||||
channel: "discord",
|
||||
accountId: "default",
|
||||
conversationId: "1479098716916023408",
|
||||
});
|
||||
|
||||
getActivePluginRegistryVersionMock.mockReturnValue(11);
|
||||
bindingRegistry.resolveConfiguredBindingRecord({
|
||||
cfg: cfg as never,
|
||||
channel: "discord",
|
||||
accountId: "default",
|
||||
conversationId: "1479098716916023408",
|
||||
});
|
||||
|
||||
expect(plugin.bindings?.compileConfiguredBinding).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@ -0,0 +1,155 @@
|
||||
import {
|
||||
buildConfiguredAcpSessionKey,
|
||||
normalizeBindingConfig,
|
||||
normalizeMode,
|
||||
normalizeText,
|
||||
parseConfiguredAcpSessionKey,
|
||||
toConfiguredAcpBindingRecord,
|
||||
type ConfiguredAcpBindingSpec,
|
||||
} from "../../acp/persistent-bindings.types.js";
|
||||
import {
|
||||
resolveAgentConfig,
|
||||
resolveAgentWorkspaceDir,
|
||||
resolveDefaultAgentId,
|
||||
} from "../../agents/agent-scope.js";
|
||||
import type { OpenClawConfig } from "../../config/config.js";
|
||||
import type {
|
||||
ConfiguredBindingRuleConfig,
|
||||
ConfiguredBindingTargetFactory,
|
||||
} from "./binding-types.js";
|
||||
import type { ConfiguredBindingConsumer } from "./configured-binding-consumers.js";
|
||||
import type { ChannelConfiguredBindingConversationRef } from "./types.adapters.js";
|
||||
|
||||
function resolveAgentRuntimeAcpDefaults(params: { cfg: OpenClawConfig; ownerAgentId: string }): {
|
||||
acpAgentId?: string;
|
||||
mode?: string;
|
||||
cwd?: string;
|
||||
backend?: string;
|
||||
} {
|
||||
const agent = params.cfg.agents?.list?.find(
|
||||
(entry) => entry.id?.trim().toLowerCase() === params.ownerAgentId.toLowerCase(),
|
||||
);
|
||||
if (!agent || agent.runtime?.type !== "acp") {
|
||||
return {};
|
||||
}
|
||||
return {
|
||||
acpAgentId: normalizeText(agent.runtime.acp?.agent),
|
||||
mode: normalizeText(agent.runtime.acp?.mode),
|
||||
cwd: normalizeText(agent.runtime.acp?.cwd),
|
||||
backend: normalizeText(agent.runtime.acp?.backend),
|
||||
};
|
||||
}
|
||||
|
||||
function resolveConfiguredBindingWorkspaceCwd(params: {
|
||||
cfg: OpenClawConfig;
|
||||
agentId: string;
|
||||
}): string | undefined {
|
||||
const explicitAgentWorkspace = normalizeText(
|
||||
resolveAgentConfig(params.cfg, params.agentId)?.workspace,
|
||||
);
|
||||
if (explicitAgentWorkspace) {
|
||||
return resolveAgentWorkspaceDir(params.cfg, params.agentId);
|
||||
}
|
||||
if (params.agentId === resolveDefaultAgentId(params.cfg)) {
|
||||
const defaultWorkspace = normalizeText(params.cfg.agents?.defaults?.workspace);
|
||||
if (defaultWorkspace) {
|
||||
return resolveAgentWorkspaceDir(params.cfg, params.agentId);
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function buildConfiguredAcpSpec(params: {
|
||||
channel: string;
|
||||
accountId: string;
|
||||
conversation: ChannelConfiguredBindingConversationRef;
|
||||
agentId: string;
|
||||
acpAgentId?: string;
|
||||
mode: "persistent" | "oneshot";
|
||||
cwd?: string;
|
||||
backend?: string;
|
||||
label?: string;
|
||||
}): ConfiguredAcpBindingSpec {
|
||||
return {
|
||||
channel: params.channel as ConfiguredAcpBindingSpec["channel"],
|
||||
accountId: params.accountId,
|
||||
conversationId: params.conversation.conversationId,
|
||||
parentConversationId: params.conversation.parentConversationId,
|
||||
agentId: params.agentId,
|
||||
acpAgentId: params.acpAgentId,
|
||||
mode: params.mode,
|
||||
cwd: params.cwd,
|
||||
backend: params.backend,
|
||||
label: params.label,
|
||||
};
|
||||
}
|
||||
|
||||
function buildAcpTargetFactory(params: {
|
||||
cfg: OpenClawConfig;
|
||||
binding: ConfiguredBindingRuleConfig;
|
||||
channel: string;
|
||||
agentId: string;
|
||||
}): ConfiguredBindingTargetFactory | null {
|
||||
if (params.binding.type !== "acp") {
|
||||
return null;
|
||||
}
|
||||
const runtimeDefaults = resolveAgentRuntimeAcpDefaults({
|
||||
cfg: params.cfg,
|
||||
ownerAgentId: params.agentId,
|
||||
});
|
||||
const bindingOverrides = normalizeBindingConfig(params.binding.acp);
|
||||
const mode = normalizeMode(bindingOverrides.mode ?? runtimeDefaults.mode);
|
||||
const cwd =
|
||||
bindingOverrides.cwd ??
|
||||
runtimeDefaults.cwd ??
|
||||
resolveConfiguredBindingWorkspaceCwd({
|
||||
cfg: params.cfg,
|
||||
agentId: params.agentId,
|
||||
});
|
||||
const backend = bindingOverrides.backend ?? runtimeDefaults.backend;
|
||||
const label = bindingOverrides.label;
|
||||
const acpAgentId = normalizeText(runtimeDefaults.acpAgentId);
|
||||
|
||||
return {
|
||||
driverId: "acp",
|
||||
materialize: ({ accountId, conversation }) => {
|
||||
const spec = buildConfiguredAcpSpec({
|
||||
channel: params.channel,
|
||||
accountId,
|
||||
conversation,
|
||||
agentId: params.agentId,
|
||||
acpAgentId,
|
||||
mode,
|
||||
cwd,
|
||||
backend,
|
||||
label,
|
||||
});
|
||||
const record = toConfiguredAcpBindingRecord(spec);
|
||||
return {
|
||||
record,
|
||||
statefulTarget: {
|
||||
kind: "stateful",
|
||||
driverId: "acp",
|
||||
sessionKey: buildConfiguredAcpSessionKey(spec),
|
||||
agentId: params.agentId,
|
||||
...(label ? { label } : {}),
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export const acpConfiguredBindingConsumer: ConfiguredBindingConsumer = {
|
||||
id: "acp",
|
||||
supports: (binding) => binding.type === "acp",
|
||||
buildTargetFactory: (params) =>
|
||||
buildAcpTargetFactory({
|
||||
cfg: params.cfg,
|
||||
binding: params.binding,
|
||||
channel: params.channel,
|
||||
agentId: params.agentId,
|
||||
}),
|
||||
parseSessionKey: ({ sessionKey }) => parseConfiguredAcpSessionKey(sessionKey),
|
||||
matchesSessionKey: ({ sessionKey, materializedTarget }) =>
|
||||
materializedTarget.record.targetSessionKey === sessionKey,
|
||||
};
|
||||
@ -0,0 +1,102 @@
|
||||
import {
|
||||
ensureConfiguredAcpBindingReady,
|
||||
ensureConfiguredAcpBindingSession,
|
||||
resetAcpSessionInPlace,
|
||||
} from "../../acp/persistent-bindings.lifecycle.js";
|
||||
import { resolveConfiguredAcpBindingSpecBySessionKey } from "../../acp/persistent-bindings.resolve.js";
|
||||
import { resolveConfiguredAcpBindingSpecFromRecord } from "../../acp/persistent-bindings.types.js";
|
||||
import { readAcpSessionEntry } from "../../acp/runtime/session-meta.js";
|
||||
import type { OpenClawConfig } from "../../config/config.js";
|
||||
import type {
|
||||
ConfiguredBindingResolution,
|
||||
StatefulBindingTargetDescriptor,
|
||||
} from "./binding-types.js";
|
||||
import type {
|
||||
StatefulBindingTargetDriver,
|
||||
StatefulBindingTargetResetResult,
|
||||
StatefulBindingTargetReadyResult,
|
||||
StatefulBindingTargetSessionResult,
|
||||
} from "./stateful-target-drivers.js";
|
||||
|
||||
function toAcpStatefulBindingTargetDescriptor(params: {
|
||||
cfg: OpenClawConfig;
|
||||
sessionKey: string;
|
||||
}): StatefulBindingTargetDescriptor | null {
|
||||
const meta = readAcpSessionEntry(params)?.acp;
|
||||
const metaAgentId = meta?.agent?.trim();
|
||||
if (metaAgentId) {
|
||||
return {
|
||||
kind: "stateful",
|
||||
driverId: "acp",
|
||||
sessionKey: params.sessionKey,
|
||||
agentId: metaAgentId,
|
||||
};
|
||||
}
|
||||
const spec = resolveConfiguredAcpBindingSpecBySessionKey(params);
|
||||
if (!spec) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
kind: "stateful",
|
||||
driverId: "acp",
|
||||
sessionKey: params.sessionKey,
|
||||
agentId: spec.agentId,
|
||||
...(spec.label ? { label: spec.label } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
async function ensureAcpTargetReady(params: {
|
||||
cfg: OpenClawConfig;
|
||||
bindingResolution: ConfiguredBindingResolution;
|
||||
}): Promise<StatefulBindingTargetReadyResult> {
|
||||
const configuredBinding = resolveConfiguredAcpBindingSpecFromRecord(
|
||||
params.bindingResolution.record,
|
||||
);
|
||||
if (!configuredBinding) {
|
||||
return {
|
||||
ok: false,
|
||||
error: "Configured ACP binding unavailable",
|
||||
};
|
||||
}
|
||||
return await ensureConfiguredAcpBindingReady({
|
||||
cfg: params.cfg,
|
||||
configuredBinding: {
|
||||
spec: configuredBinding,
|
||||
record: params.bindingResolution.record,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function ensureAcpTargetSession(params: {
|
||||
cfg: OpenClawConfig;
|
||||
bindingResolution: ConfiguredBindingResolution;
|
||||
}): Promise<StatefulBindingTargetSessionResult> {
|
||||
const spec = resolveConfiguredAcpBindingSpecFromRecord(params.bindingResolution.record);
|
||||
if (!spec) {
|
||||
return {
|
||||
ok: false,
|
||||
sessionKey: params.bindingResolution.statefulTarget.sessionKey,
|
||||
error: "Configured ACP binding unavailable",
|
||||
};
|
||||
}
|
||||
return await ensureConfiguredAcpBindingSession({
|
||||
cfg: params.cfg,
|
||||
spec,
|
||||
});
|
||||
}
|
||||
|
||||
async function resetAcpTargetInPlace(params: {
|
||||
cfg: OpenClawConfig;
|
||||
sessionKey: string;
|
||||
reason: "new" | "reset";
|
||||
}): Promise<StatefulBindingTargetResetResult> {
|
||||
return await resetAcpSessionInPlace(params);
|
||||
}
|
||||
|
||||
export const acpStatefulBindingTargetDriver: StatefulBindingTargetDriver = {
|
||||
id: "acp",
|
||||
ensureReady: ensureAcpTargetReady,
|
||||
ensureSession: ensureAcpTargetSession,
|
||||
resolveTargetBySessionKey: toAcpStatefulBindingTargetDescriptor,
|
||||
resetInPlace: resetAcpTargetInPlace,
|
||||
};
|
||||
@ -0,0 +1,14 @@
|
||||
import type { ChannelConfiguredBindingProvider } from "./types.adapters.js";
|
||||
import type { ChannelPlugin } from "./types.plugin.js";
|
||||
|
||||
export function resolveChannelConfiguredBindingProvider(
|
||||
plugin:
|
||||
| Pick<ChannelPlugin, "bindings">
|
||||
| {
|
||||
bindings?: ChannelConfiguredBindingProvider;
|
||||
}
|
||||
| null
|
||||
| undefined,
|
||||
): ChannelConfiguredBindingProvider | undefined {
|
||||
return plugin?.bindings;
|
||||
}
|
||||
@ -0,0 +1,46 @@
|
||||
import { ensureConfiguredBindingBuiltinsRegistered } from "./configured-binding-builtins.js";
|
||||
import {
|
||||
primeConfiguredBindingRegistry as primeConfiguredBindingRegistryRaw,
|
||||
resolveConfiguredBinding as resolveConfiguredBindingRaw,
|
||||
resolveConfiguredBindingRecord as resolveConfiguredBindingRecordRaw,
|
||||
resolveConfiguredBindingRecordBySessionKey as resolveConfiguredBindingRecordBySessionKeyRaw,
|
||||
resolveConfiguredBindingRecordForConversation as resolveConfiguredBindingRecordForConversationRaw,
|
||||
} from "./configured-binding-registry.js";
|
||||
|
||||
// Thin public wrapper around the configured-binding registry. Runtime plugin
|
||||
// conversation bindings use a separate approval-driven path in src/plugins/.
|
||||
|
||||
export function primeConfiguredBindingRegistry(
|
||||
...args: Parameters<typeof primeConfiguredBindingRegistryRaw>
|
||||
): ReturnType<typeof primeConfiguredBindingRegistryRaw> {
|
||||
ensureConfiguredBindingBuiltinsRegistered();
|
||||
return primeConfiguredBindingRegistryRaw(...args);
|
||||
}
|
||||
|
||||
export function resolveConfiguredBindingRecord(
|
||||
...args: Parameters<typeof resolveConfiguredBindingRecordRaw>
|
||||
): ReturnType<typeof resolveConfiguredBindingRecordRaw> {
|
||||
ensureConfiguredBindingBuiltinsRegistered();
|
||||
return resolveConfiguredBindingRecordRaw(...args);
|
||||
}
|
||||
|
||||
export function resolveConfiguredBindingRecordForConversation(
|
||||
...args: Parameters<typeof resolveConfiguredBindingRecordForConversationRaw>
|
||||
): ReturnType<typeof resolveConfiguredBindingRecordForConversationRaw> {
|
||||
ensureConfiguredBindingBuiltinsRegistered();
|
||||
return resolveConfiguredBindingRecordForConversationRaw(...args);
|
||||
}
|
||||
|
||||
export function resolveConfiguredBinding(
|
||||
...args: Parameters<typeof resolveConfiguredBindingRaw>
|
||||
): ReturnType<typeof resolveConfiguredBindingRaw> {
|
||||
ensureConfiguredBindingBuiltinsRegistered();
|
||||
return resolveConfiguredBindingRaw(...args);
|
||||
}
|
||||
|
||||
export function resolveConfiguredBindingRecordBySessionKey(
|
||||
...args: Parameters<typeof resolveConfiguredBindingRecordBySessionKeyRaw>
|
||||
): ReturnType<typeof resolveConfiguredBindingRecordBySessionKeyRaw> {
|
||||
ensureConfiguredBindingBuiltinsRegistered();
|
||||
return resolveConfiguredBindingRecordBySessionKeyRaw(...args);
|
||||
}
|
||||
@ -0,0 +1,91 @@
|
||||
import type { OpenClawConfig } from "../../config/config.js";
|
||||
import type { ConversationRef } from "../../infra/outbound/session-binding-service.js";
|
||||
import type { ResolvedAgentRoute } from "../../routing/resolve-route.js";
|
||||
import { deriveLastRoutePolicy } from "../../routing/resolve-route.js";
|
||||
import { resolveAgentIdFromSessionKey } from "../../routing/session-key.js";
|
||||
import { resolveConfiguredBinding } from "./binding-registry.js";
|
||||
import { ensureConfiguredBindingTargetReady } from "./binding-targets.js";
|
||||
import type { ConfiguredBindingResolution } from "./binding-types.js";
|
||||
|
||||
export type ConfiguredBindingRouteResult = {
|
||||
bindingResolution: ConfiguredBindingResolution | null;
|
||||
route: ResolvedAgentRoute;
|
||||
boundSessionKey?: string;
|
||||
boundAgentId?: string;
|
||||
};
|
||||
|
||||
type ConfiguredBindingRouteConversationInput =
|
||||
| {
|
||||
conversation: ConversationRef;
|
||||
}
|
||||
| {
|
||||
channel: string;
|
||||
accountId: string;
|
||||
conversationId: string;
|
||||
parentConversationId?: string;
|
||||
};
|
||||
|
||||
function resolveConfiguredBindingConversationRef(
|
||||
params: ConfiguredBindingRouteConversationInput,
|
||||
): ConversationRef {
|
||||
if ("conversation" in params) {
|
||||
return params.conversation;
|
||||
}
|
||||
return {
|
||||
channel: params.channel,
|
||||
accountId: params.accountId,
|
||||
conversationId: params.conversationId,
|
||||
parentConversationId: params.parentConversationId,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveConfiguredBindingRoute(
|
||||
params: {
|
||||
cfg: OpenClawConfig;
|
||||
route: ResolvedAgentRoute;
|
||||
} & ConfiguredBindingRouteConversationInput,
|
||||
): ConfiguredBindingRouteResult {
|
||||
const bindingResolution =
|
||||
resolveConfiguredBinding({
|
||||
cfg: params.cfg,
|
||||
conversation: resolveConfiguredBindingConversationRef(params),
|
||||
}) ?? null;
|
||||
if (!bindingResolution) {
|
||||
return {
|
||||
bindingResolution: null,
|
||||
route: params.route,
|
||||
};
|
||||
}
|
||||
|
||||
const boundSessionKey = bindingResolution.statefulTarget.sessionKey.trim();
|
||||
if (!boundSessionKey) {
|
||||
return {
|
||||
bindingResolution,
|
||||
route: params.route,
|
||||
};
|
||||
}
|
||||
const boundAgentId =
|
||||
resolveAgentIdFromSessionKey(boundSessionKey) || bindingResolution.statefulTarget.agentId;
|
||||
return {
|
||||
bindingResolution,
|
||||
boundSessionKey,
|
||||
boundAgentId,
|
||||
route: {
|
||||
...params.route,
|
||||
sessionKey: boundSessionKey,
|
||||
agentId: boundAgentId,
|
||||
lastRoutePolicy: deriveLastRoutePolicy({
|
||||
sessionKey: boundSessionKey,
|
||||
mainSessionKey: params.route.mainSessionKey,
|
||||
}),
|
||||
matchedBy: "binding.channel",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function ensureConfiguredBindingRouteReady(params: {
|
||||
cfg: OpenClawConfig;
|
||||
bindingResolution: ConfiguredBindingResolution | null;
|
||||
}): Promise<{ ok: true } | { ok: false; error: string }> {
|
||||
return await ensureConfiguredBindingTargetReady(params);
|
||||
}
|
||||
@ -0,0 +1,209 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
ensureConfiguredBindingTargetReady,
|
||||
ensureConfiguredBindingTargetSession,
|
||||
resetConfiguredBindingTargetInPlace,
|
||||
} from "./binding-targets.js";
|
||||
import type { ConfiguredBindingResolution } from "./binding-types.js";
|
||||
import {
|
||||
registerStatefulBindingTargetDriver,
|
||||
unregisterStatefulBindingTargetDriver,
|
||||
type StatefulBindingTargetDriver,
|
||||
} from "./stateful-target-drivers.js";
|
||||
|
||||
function createBindingResolution(driverId: string): ConfiguredBindingResolution {
|
||||
return {
|
||||
conversation: {
|
||||
channel: "discord",
|
||||
accountId: "default",
|
||||
conversationId: "123",
|
||||
},
|
||||
compiledBinding: {
|
||||
channel: "discord",
|
||||
binding: {
|
||||
type: "acp" as const,
|
||||
agentId: "codex",
|
||||
match: {
|
||||
channel: "discord",
|
||||
peer: {
|
||||
kind: "channel" as const,
|
||||
id: "123",
|
||||
},
|
||||
},
|
||||
acp: {
|
||||
mode: "persistent",
|
||||
},
|
||||
},
|
||||
bindingConversationId: "123",
|
||||
target: {
|
||||
conversationId: "123",
|
||||
},
|
||||
agentId: "codex",
|
||||
provider: {
|
||||
compileConfiguredBinding: () => ({
|
||||
conversationId: "123",
|
||||
}),
|
||||
matchInboundConversation: () => ({
|
||||
conversationId: "123",
|
||||
}),
|
||||
},
|
||||
targetFactory: {
|
||||
driverId,
|
||||
materialize: () => ({
|
||||
record: {
|
||||
bindingId: "binding:123",
|
||||
targetSessionKey: `agent:codex:${driverId}`,
|
||||
targetKind: "session",
|
||||
conversation: {
|
||||
channel: "discord",
|
||||
accountId: "default",
|
||||
conversationId: "123",
|
||||
},
|
||||
status: "active",
|
||||
boundAt: 0,
|
||||
},
|
||||
statefulTarget: {
|
||||
kind: "stateful",
|
||||
driverId,
|
||||
sessionKey: `agent:codex:${driverId}`,
|
||||
agentId: "codex",
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
match: {
|
||||
conversationId: "123",
|
||||
},
|
||||
record: {
|
||||
bindingId: "binding:123",
|
||||
targetSessionKey: `agent:codex:${driverId}`,
|
||||
targetKind: "session",
|
||||
conversation: {
|
||||
channel: "discord",
|
||||
accountId: "default",
|
||||
conversationId: "123",
|
||||
},
|
||||
status: "active",
|
||||
boundAt: 0,
|
||||
},
|
||||
statefulTarget: {
|
||||
kind: "stateful",
|
||||
driverId,
|
||||
sessionKey: `agent:codex:${driverId}`,
|
||||
agentId: "codex",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
unregisterStatefulBindingTargetDriver("test-driver");
|
||||
});
|
||||
|
||||
describe("binding target drivers", () => {
|
||||
it("delegates ensureReady and ensureSession to the resolved driver", async () => {
|
||||
const ensureReady = vi.fn(async () => ({ ok: true as const }));
|
||||
const ensureSession = vi.fn(async () => ({
|
||||
ok: true as const,
|
||||
sessionKey: "agent:codex:test-driver",
|
||||
}));
|
||||
const driver: StatefulBindingTargetDriver = {
|
||||
id: "test-driver",
|
||||
ensureReady,
|
||||
ensureSession,
|
||||
};
|
||||
registerStatefulBindingTargetDriver(driver);
|
||||
|
||||
const bindingResolution = createBindingResolution("test-driver");
|
||||
await expect(
|
||||
ensureConfiguredBindingTargetReady({
|
||||
cfg: {} as never,
|
||||
bindingResolution,
|
||||
}),
|
||||
).resolves.toEqual({ ok: true });
|
||||
await expect(
|
||||
ensureConfiguredBindingTargetSession({
|
||||
cfg: {} as never,
|
||||
bindingResolution,
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
ok: true,
|
||||
sessionKey: "agent:codex:test-driver",
|
||||
});
|
||||
|
||||
expect(ensureReady).toHaveBeenCalledTimes(1);
|
||||
expect(ensureReady).toHaveBeenCalledWith({
|
||||
cfg: {} as never,
|
||||
bindingResolution,
|
||||
});
|
||||
expect(ensureSession).toHaveBeenCalledTimes(1);
|
||||
expect(ensureSession).toHaveBeenCalledWith({
|
||||
cfg: {} as never,
|
||||
bindingResolution,
|
||||
});
|
||||
});
|
||||
|
||||
it("resolves resetInPlace through the driver session-key lookup", async () => {
|
||||
const resetInPlace = vi.fn(async () => ({ ok: true as const }));
|
||||
const driver: StatefulBindingTargetDriver = {
|
||||
id: "test-driver",
|
||||
ensureReady: async () => ({ ok: true }),
|
||||
ensureSession: async () => ({
|
||||
ok: true,
|
||||
sessionKey: "agent:codex:test-driver",
|
||||
}),
|
||||
resolveTargetBySessionKey: ({ sessionKey }) => ({
|
||||
kind: "stateful",
|
||||
driverId: "test-driver",
|
||||
sessionKey,
|
||||
agentId: "codex",
|
||||
}),
|
||||
resetInPlace,
|
||||
};
|
||||
registerStatefulBindingTargetDriver(driver);
|
||||
|
||||
await expect(
|
||||
resetConfiguredBindingTargetInPlace({
|
||||
cfg: {} as never,
|
||||
sessionKey: "agent:codex:test-driver",
|
||||
reason: "reset",
|
||||
}),
|
||||
).resolves.toEqual({ ok: true });
|
||||
|
||||
expect(resetInPlace).toHaveBeenCalledTimes(1);
|
||||
expect(resetInPlace).toHaveBeenCalledWith({
|
||||
cfg: {} as never,
|
||||
sessionKey: "agent:codex:test-driver",
|
||||
reason: "reset",
|
||||
bindingTarget: {
|
||||
kind: "stateful",
|
||||
driverId: "test-driver",
|
||||
sessionKey: "agent:codex:test-driver",
|
||||
agentId: "codex",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("returns a typed error when no driver is registered", async () => {
|
||||
const bindingResolution = createBindingResolution("missing-driver");
|
||||
|
||||
await expect(
|
||||
ensureConfiguredBindingTargetReady({
|
||||
cfg: {} as never,
|
||||
bindingResolution,
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
ok: false,
|
||||
error: "Configured binding target driver unavailable: missing-driver",
|
||||
});
|
||||
await expect(
|
||||
ensureConfiguredBindingTargetSession({
|
||||
cfg: {} as never,
|
||||
bindingResolution,
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
ok: false,
|
||||
sessionKey: "agent:codex:missing-driver",
|
||||
error: "Configured binding target driver unavailable: missing-driver",
|
||||
});
|
||||
});
|
||||
});
|
||||
@ -0,0 +1,69 @@
|
||||
import type { OpenClawConfig } from "../../config/config.js";
|
||||
import type { ConfiguredBindingResolution } from "./binding-types.js";
|
||||
import { ensureStatefulTargetBuiltinsRegistered } from "./stateful-target-builtins.js";
|
||||
import {
|
||||
getStatefulBindingTargetDriver,
|
||||
resolveStatefulBindingTargetBySessionKey,
|
||||
} from "./stateful-target-drivers.js";
|
||||
|
||||
export async function ensureConfiguredBindingTargetReady(params: {
|
||||
cfg: OpenClawConfig;
|
||||
bindingResolution: ConfiguredBindingResolution | null;
|
||||
}): Promise<{ ok: true } | { ok: false; error: string }> {
|
||||
ensureStatefulTargetBuiltinsRegistered();
|
||||
if (!params.bindingResolution) {
|
||||
return { ok: true };
|
||||
}
|
||||
const driver = getStatefulBindingTargetDriver(params.bindingResolution.statefulTarget.driverId);
|
||||
if (!driver) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `Configured binding target driver unavailable: ${params.bindingResolution.statefulTarget.driverId}`,
|
||||
};
|
||||
}
|
||||
return await driver.ensureReady({
|
||||
cfg: params.cfg,
|
||||
bindingResolution: params.bindingResolution,
|
||||
});
|
||||
}
|
||||
|
||||
export async function resetConfiguredBindingTargetInPlace(params: {
|
||||
cfg: OpenClawConfig;
|
||||
sessionKey: string;
|
||||
reason: "new" | "reset";
|
||||
}): Promise<{ ok: true } | { ok: false; skipped?: boolean; error?: string }> {
|
||||
ensureStatefulTargetBuiltinsRegistered();
|
||||
const resolved = resolveStatefulBindingTargetBySessionKey({
|
||||
cfg: params.cfg,
|
||||
sessionKey: params.sessionKey,
|
||||
});
|
||||
if (!resolved?.driver.resetInPlace) {
|
||||
return {
|
||||
ok: false,
|
||||
skipped: true,
|
||||
};
|
||||
}
|
||||
return await resolved.driver.resetInPlace({
|
||||
...params,
|
||||
bindingTarget: resolved.bindingTarget,
|
||||
});
|
||||
}
|
||||
|
||||
export async function ensureConfiguredBindingTargetSession(params: {
|
||||
cfg: OpenClawConfig;
|
||||
bindingResolution: ConfiguredBindingResolution;
|
||||
}): Promise<{ ok: true; sessionKey: string } | { ok: false; sessionKey: string; error: string }> {
|
||||
ensureStatefulTargetBuiltinsRegistered();
|
||||
const driver = getStatefulBindingTargetDriver(params.bindingResolution.statefulTarget.driverId);
|
||||
if (!driver) {
|
||||
return {
|
||||
ok: false,
|
||||
sessionKey: params.bindingResolution.statefulTarget.sessionKey,
|
||||
error: `Configured binding target driver unavailable: ${params.bindingResolution.statefulTarget.driverId}`,
|
||||
};
|
||||
}
|
||||
return await driver.ensureSession({
|
||||
cfg: params.cfg,
|
||||
bindingResolution: params.bindingResolution,
|
||||
});
|
||||
}
|
||||
@ -0,0 +1,53 @@
|
||||
import type { AgentBinding } from "../../config/types.js";
|
||||
import type {
|
||||
ConversationRef,
|
||||
SessionBindingRecord,
|
||||
} from "../../infra/outbound/session-binding-service.js";
|
||||
import type {
|
||||
ChannelConfiguredBindingConversationRef,
|
||||
ChannelConfiguredBindingMatch,
|
||||
ChannelConfiguredBindingProvider,
|
||||
} from "./types.adapters.js";
|
||||
import type { ChannelId } from "./types.js";
|
||||
|
||||
export type ConfiguredBindingConversation = ConversationRef;
|
||||
export type ConfiguredBindingChannel = ChannelId;
|
||||
export type ConfiguredBindingRuleConfig = AgentBinding;
|
||||
|
||||
export type StatefulBindingTargetDescriptor = {
|
||||
kind: "stateful";
|
||||
driverId: string;
|
||||
sessionKey: string;
|
||||
agentId: string;
|
||||
label?: string;
|
||||
};
|
||||
|
||||
export type ConfiguredBindingRecordResolution = {
|
||||
record: SessionBindingRecord;
|
||||
statefulTarget: StatefulBindingTargetDescriptor;
|
||||
};
|
||||
|
||||
export type ConfiguredBindingTargetFactory = {
|
||||
driverId: string;
|
||||
materialize: (params: {
|
||||
accountId: string;
|
||||
conversation: ChannelConfiguredBindingConversationRef;
|
||||
}) => ConfiguredBindingRecordResolution;
|
||||
};
|
||||
|
||||
export type CompiledConfiguredBinding = {
|
||||
channel: ConfiguredBindingChannel;
|
||||
accountPattern?: string;
|
||||
binding: ConfiguredBindingRuleConfig;
|
||||
bindingConversationId: string;
|
||||
target: ChannelConfiguredBindingConversationRef;
|
||||
agentId: string;
|
||||
provider: ChannelConfiguredBindingProvider;
|
||||
targetFactory: ConfiguredBindingTargetFactory;
|
||||
};
|
||||
|
||||
export type ConfiguredBindingResolution = ConfiguredBindingRecordResolution & {
|
||||
conversation: ConfiguredBindingConversation;
|
||||
compiledBinding: CompiledConfiguredBinding;
|
||||
match: ChannelConfiguredBindingMatch;
|
||||
};
|
||||
@ -0,0 +1,13 @@
|
||||
import { acpConfiguredBindingConsumer } from "./acp-configured-binding-consumer.js";
|
||||
import {
|
||||
registerConfiguredBindingConsumer,
|
||||
unregisterConfiguredBindingConsumer,
|
||||
} from "./configured-binding-consumers.js";
|
||||
|
||||
export function ensureConfiguredBindingBuiltinsRegistered(): void {
|
||||
registerConfiguredBindingConsumer(acpConfiguredBindingConsumer);
|
||||
}
|
||||
|
||||
export function resetConfiguredBindingBuiltinsForTesting(): void {
|
||||
unregisterConfiguredBindingConsumer(acpConfiguredBindingConsumer.id);
|
||||
}
|
||||
@ -0,0 +1,240 @@
|
||||
import { listConfiguredBindings } from "../../config/bindings.js";
|
||||
import type { OpenClawConfig } from "../../config/config.js";
|
||||
import { getActivePluginRegistry, getActivePluginRegistryVersion } from "../../plugins/runtime.js";
|
||||
import { pickFirstExistingAgentId } from "../../routing/resolve-route.js";
|
||||
import { resolveChannelConfiguredBindingProvider } from "./binding-provider.js";
|
||||
import type { CompiledConfiguredBinding, ConfiguredBindingChannel } from "./binding-types.js";
|
||||
import { resolveConfiguredBindingConsumer } from "./configured-binding-consumers.js";
|
||||
import { getChannelPlugin } from "./index.js";
|
||||
import type {
|
||||
ChannelConfiguredBindingConversationRef,
|
||||
ChannelConfiguredBindingProvider,
|
||||
} from "./types.adapters.js";
|
||||
|
||||
// Configured bindings are channel-owned rules compiled from config, separate
|
||||
// from runtime plugin-owned conversation bindings.
|
||||
|
||||
type ChannelPluginLike = NonNullable<ReturnType<typeof getChannelPlugin>>;
|
||||
|
||||
export type CompiledConfiguredBindingRegistry = {
|
||||
rulesByChannel: Map<ConfiguredBindingChannel, CompiledConfiguredBinding[]>;
|
||||
};
|
||||
|
||||
type CachedCompiledConfiguredBindingRegistry = {
|
||||
registryVersion: number;
|
||||
registry: CompiledConfiguredBindingRegistry;
|
||||
};
|
||||
|
||||
const compiledRegistryCache = new WeakMap<
|
||||
OpenClawConfig,
|
||||
CachedCompiledConfiguredBindingRegistry
|
||||
>();
|
||||
|
||||
function findChannelPlugin(params: {
|
||||
registry:
|
||||
| {
|
||||
channels?: Array<{ plugin?: ChannelPluginLike | null } | null> | null;
|
||||
}
|
||||
| null
|
||||
| undefined;
|
||||
channel: string;
|
||||
}): ChannelPluginLike | undefined {
|
||||
return (
|
||||
params.registry?.channels?.find((entry) => entry?.plugin?.id === params.channel)?.plugin ??
|
||||
undefined
|
||||
);
|
||||
}
|
||||
|
||||
function resolveLoadedChannelPlugin(channel: string) {
|
||||
const normalized = channel.trim().toLowerCase();
|
||||
if (!normalized) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const current = getChannelPlugin(normalized as ConfiguredBindingChannel);
|
||||
if (current) {
|
||||
return current;
|
||||
}
|
||||
|
||||
return findChannelPlugin({
|
||||
registry: getActivePluginRegistry(),
|
||||
channel: normalized,
|
||||
});
|
||||
}
|
||||
|
||||
function resolveConfiguredBindingAdapter(channel: string): {
|
||||
channel: ConfiguredBindingChannel;
|
||||
provider: ChannelConfiguredBindingProvider;
|
||||
} | null {
|
||||
const normalized = channel.trim().toLowerCase();
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
const plugin = resolveLoadedChannelPlugin(normalized);
|
||||
const provider = resolveChannelConfiguredBindingProvider(plugin);
|
||||
if (
|
||||
!plugin ||
|
||||
!provider ||
|
||||
!provider.compileConfiguredBinding ||
|
||||
!provider.matchInboundConversation
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
channel: plugin.id,
|
||||
provider,
|
||||
};
|
||||
}
|
||||
|
||||
function resolveBindingConversationId(binding: {
|
||||
match?: { peer?: { id?: string } };
|
||||
}): string | null {
|
||||
const id = binding.match?.peer?.id?.trim();
|
||||
return id ? id : null;
|
||||
}
|
||||
|
||||
function compileConfiguredBindingTarget(params: {
|
||||
provider: ChannelConfiguredBindingProvider;
|
||||
binding: CompiledConfiguredBinding["binding"];
|
||||
conversationId: string;
|
||||
}): ChannelConfiguredBindingConversationRef | null {
|
||||
return params.provider.compileConfiguredBinding({
|
||||
binding: params.binding,
|
||||
conversationId: params.conversationId,
|
||||
});
|
||||
}
|
||||
|
||||
function compileConfiguredBindingRule(params: {
|
||||
cfg: OpenClawConfig;
|
||||
channel: ConfiguredBindingChannel;
|
||||
binding: CompiledConfiguredBinding["binding"];
|
||||
target: ChannelConfiguredBindingConversationRef;
|
||||
bindingConversationId: string;
|
||||
provider: ChannelConfiguredBindingProvider;
|
||||
}): CompiledConfiguredBinding | null {
|
||||
const agentId = pickFirstExistingAgentId(params.cfg, params.binding.agentId ?? "main");
|
||||
const consumer = resolveConfiguredBindingConsumer(params.binding);
|
||||
if (!consumer) {
|
||||
return null;
|
||||
}
|
||||
const targetFactory = consumer.buildTargetFactory({
|
||||
cfg: params.cfg,
|
||||
binding: params.binding,
|
||||
channel: params.channel,
|
||||
agentId,
|
||||
target: params.target,
|
||||
bindingConversationId: params.bindingConversationId,
|
||||
});
|
||||
if (!targetFactory) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
channel: params.channel,
|
||||
accountPattern: params.binding.match.accountId?.trim() || undefined,
|
||||
binding: params.binding,
|
||||
bindingConversationId: params.bindingConversationId,
|
||||
target: params.target,
|
||||
agentId,
|
||||
provider: params.provider,
|
||||
targetFactory,
|
||||
};
|
||||
}
|
||||
|
||||
function pushCompiledRule(
|
||||
target: Map<ConfiguredBindingChannel, CompiledConfiguredBinding[]>,
|
||||
rule: CompiledConfiguredBinding,
|
||||
) {
|
||||
const existing = target.get(rule.channel);
|
||||
if (existing) {
|
||||
existing.push(rule);
|
||||
return;
|
||||
}
|
||||
target.set(rule.channel, [rule]);
|
||||
}
|
||||
|
||||
function compileConfiguredBindingRegistry(params: {
|
||||
cfg: OpenClawConfig;
|
||||
}): CompiledConfiguredBindingRegistry {
|
||||
const rulesByChannel = new Map<ConfiguredBindingChannel, CompiledConfiguredBinding[]>();
|
||||
|
||||
for (const binding of listConfiguredBindings(params.cfg)) {
|
||||
const bindingConversationId = resolveBindingConversationId(binding);
|
||||
if (!bindingConversationId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const resolvedChannel = resolveConfiguredBindingAdapter(binding.match.channel);
|
||||
if (!resolvedChannel) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const target = compileConfiguredBindingTarget({
|
||||
provider: resolvedChannel.provider,
|
||||
binding,
|
||||
conversationId: bindingConversationId,
|
||||
});
|
||||
if (!target) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const rule = compileConfiguredBindingRule({
|
||||
cfg: params.cfg,
|
||||
channel: resolvedChannel.channel,
|
||||
binding,
|
||||
target,
|
||||
bindingConversationId,
|
||||
provider: resolvedChannel.provider,
|
||||
});
|
||||
if (!rule) {
|
||||
continue;
|
||||
}
|
||||
pushCompiledRule(rulesByChannel, rule);
|
||||
}
|
||||
|
||||
return {
|
||||
rulesByChannel,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveCompiledBindingRegistry(
|
||||
cfg: OpenClawConfig,
|
||||
): CompiledConfiguredBindingRegistry {
|
||||
const registryVersion = getActivePluginRegistryVersion();
|
||||
const cached = compiledRegistryCache.get(cfg);
|
||||
if (cached?.registryVersion === registryVersion) {
|
||||
return cached.registry;
|
||||
}
|
||||
|
||||
const registry = compileConfiguredBindingRegistry({
|
||||
cfg,
|
||||
});
|
||||
compiledRegistryCache.set(cfg, {
|
||||
registryVersion,
|
||||
registry,
|
||||
});
|
||||
return registry;
|
||||
}
|
||||
|
||||
export function primeCompiledBindingRegistry(
|
||||
cfg: OpenClawConfig,
|
||||
): CompiledConfiguredBindingRegistry {
|
||||
const registry = compileConfiguredBindingRegistry({ cfg });
|
||||
compiledRegistryCache.set(cfg, {
|
||||
registryVersion: getActivePluginRegistryVersion(),
|
||||
registry,
|
||||
});
|
||||
return registry;
|
||||
}
|
||||
|
||||
export function countCompiledBindingRegistry(registry: CompiledConfiguredBindingRegistry): {
|
||||
bindingCount: number;
|
||||
channelCount: number;
|
||||
} {
|
||||
return {
|
||||
bindingCount: [...registry.rulesByChannel.values()].reduce(
|
||||
(sum, rules) => sum + rules.length,
|
||||
0,
|
||||
),
|
||||
channelCount: registry.rulesByChannel.size,
|
||||
};
|
||||
}
|
||||
@ -0,0 +1,69 @@
|
||||
import type { OpenClawConfig } from "../../config/config.js";
|
||||
import type {
|
||||
CompiledConfiguredBinding,
|
||||
ConfiguredBindingRecordResolution,
|
||||
ConfiguredBindingRuleConfig,
|
||||
ConfiguredBindingTargetFactory,
|
||||
} from "./binding-types.js";
|
||||
import type { ChannelConfiguredBindingConversationRef } from "./types.adapters.js";
|
||||
|
||||
export type ParsedConfiguredBindingSessionKey = {
|
||||
channel: string;
|
||||
accountId: string;
|
||||
};
|
||||
|
||||
export type ConfiguredBindingConsumer = {
|
||||
id: string;
|
||||
supports: (binding: ConfiguredBindingRuleConfig) => boolean;
|
||||
buildTargetFactory: (params: {
|
||||
cfg: OpenClawConfig;
|
||||
binding: ConfiguredBindingRuleConfig;
|
||||
channel: string;
|
||||
agentId: string;
|
||||
target: ChannelConfiguredBindingConversationRef;
|
||||
bindingConversationId: string;
|
||||
}) => ConfiguredBindingTargetFactory | null;
|
||||
parseSessionKey?: (params: { sessionKey: string }) => ParsedConfiguredBindingSessionKey | null;
|
||||
matchesSessionKey?: (params: {
|
||||
sessionKey: string;
|
||||
compiledBinding: CompiledConfiguredBinding;
|
||||
accountId: string;
|
||||
materializedTarget: ConfiguredBindingRecordResolution;
|
||||
}) => boolean;
|
||||
};
|
||||
|
||||
const registeredConfiguredBindingConsumers = new Map<string, ConfiguredBindingConsumer>();
|
||||
|
||||
export function listConfiguredBindingConsumers(): ConfiguredBindingConsumer[] {
|
||||
return [...registeredConfiguredBindingConsumers.values()];
|
||||
}
|
||||
|
||||
export function resolveConfiguredBindingConsumer(
|
||||
binding: ConfiguredBindingRuleConfig,
|
||||
): ConfiguredBindingConsumer | null {
|
||||
for (const consumer of listConfiguredBindingConsumers()) {
|
||||
if (consumer.supports(binding)) {
|
||||
return consumer;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function registerConfiguredBindingConsumer(consumer: ConfiguredBindingConsumer): void {
|
||||
const id = consumer.id.trim();
|
||||
if (!id) {
|
||||
throw new Error("Configured binding consumer id is required");
|
||||
}
|
||||
const existing = registeredConfiguredBindingConsumers.get(id);
|
||||
if (existing) {
|
||||
return;
|
||||
}
|
||||
registeredConfiguredBindingConsumers.set(id, {
|
||||
...consumer,
|
||||
id,
|
||||
});
|
||||
}
|
||||
|
||||
export function unregisterConfiguredBindingConsumer(id: string): void {
|
||||
registeredConfiguredBindingConsumers.delete(id.trim());
|
||||
}
|
||||
@ -0,0 +1,116 @@
|
||||
import type { ConversationRef } from "../../infra/outbound/session-binding-service.js";
|
||||
import { DEFAULT_ACCOUNT_ID, normalizeAccountId } from "../../routing/session-key.js";
|
||||
import type {
|
||||
CompiledConfiguredBinding,
|
||||
ConfiguredBindingChannel,
|
||||
ConfiguredBindingRecordResolution,
|
||||
} from "./binding-types.js";
|
||||
import type {
|
||||
ChannelConfiguredBindingConversationRef,
|
||||
ChannelConfiguredBindingMatch,
|
||||
} from "./types.adapters.js";
|
||||
|
||||
export function resolveAccountMatchPriority(match: string | undefined, actual: string): 0 | 1 | 2 {
|
||||
const trimmed = (match ?? "").trim();
|
||||
if (!trimmed) {
|
||||
return actual === DEFAULT_ACCOUNT_ID ? 2 : 0;
|
||||
}
|
||||
if (trimmed === "*") {
|
||||
return 1;
|
||||
}
|
||||
return normalizeAccountId(trimmed) === actual ? 2 : 0;
|
||||
}
|
||||
|
||||
function matchCompiledBindingConversation(params: {
|
||||
rule: CompiledConfiguredBinding;
|
||||
conversationId: string;
|
||||
parentConversationId?: string;
|
||||
}): ChannelConfiguredBindingMatch | null {
|
||||
return params.rule.provider.matchInboundConversation({
|
||||
binding: params.rule.binding,
|
||||
compiledBinding: params.rule.target,
|
||||
conversationId: params.conversationId,
|
||||
parentConversationId: params.parentConversationId,
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveCompiledBindingChannel(raw: string): ConfiguredBindingChannel | null {
|
||||
const normalized = raw.trim().toLowerCase();
|
||||
return normalized ? (normalized as ConfiguredBindingChannel) : null;
|
||||
}
|
||||
|
||||
export function toConfiguredBindingConversationRef(conversation: ConversationRef): {
|
||||
channel: ConfiguredBindingChannel;
|
||||
accountId: string;
|
||||
conversationId: string;
|
||||
parentConversationId?: string;
|
||||
} | null {
|
||||
const channel = resolveCompiledBindingChannel(conversation.channel);
|
||||
const conversationId = conversation.conversationId.trim();
|
||||
if (!channel || !conversationId) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
channel,
|
||||
accountId: normalizeAccountId(conversation.accountId),
|
||||
conversationId,
|
||||
parentConversationId: conversation.parentConversationId?.trim() || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function materializeConfiguredBindingRecord(params: {
|
||||
rule: CompiledConfiguredBinding;
|
||||
accountId: string;
|
||||
conversation: ChannelConfiguredBindingConversationRef;
|
||||
}): ConfiguredBindingRecordResolution {
|
||||
return params.rule.targetFactory.materialize({
|
||||
accountId: normalizeAccountId(params.accountId),
|
||||
conversation: params.conversation,
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveMatchingConfiguredBinding(params: {
|
||||
rules: CompiledConfiguredBinding[];
|
||||
conversation: ReturnType<typeof toConfiguredBindingConversationRef>;
|
||||
}): { rule: CompiledConfiguredBinding; match: ChannelConfiguredBindingMatch } | null {
|
||||
if (!params.conversation) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let wildcardMatch: {
|
||||
rule: CompiledConfiguredBinding;
|
||||
match: ChannelConfiguredBindingMatch;
|
||||
} | null = null;
|
||||
let exactMatch: { rule: CompiledConfiguredBinding; match: ChannelConfiguredBindingMatch } | null =
|
||||
null;
|
||||
|
||||
for (const rule of params.rules) {
|
||||
const accountMatchPriority = resolveAccountMatchPriority(
|
||||
rule.accountPattern,
|
||||
params.conversation.accountId,
|
||||
);
|
||||
if (accountMatchPriority === 0) {
|
||||
continue;
|
||||
}
|
||||
const match = matchCompiledBindingConversation({
|
||||
rule,
|
||||
conversationId: params.conversation.conversationId,
|
||||
parentConversationId: params.conversation.parentConversationId,
|
||||
});
|
||||
if (!match) {
|
||||
continue;
|
||||
}
|
||||
const matchPriority = match.matchPriority ?? 0;
|
||||
if (accountMatchPriority === 2) {
|
||||
if (!exactMatch || matchPriority > (exactMatch.match.matchPriority ?? 0)) {
|
||||
exactMatch = { rule, match };
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!wildcardMatch || matchPriority > (wildcardMatch.match.matchPriority ?? 0)) {
|
||||
wildcardMatch = { rule, match };
|
||||
}
|
||||
}
|
||||
|
||||
return exactMatch ?? wildcardMatch;
|
||||
}
|
||||
@ -0,0 +1,116 @@
|
||||
import type { OpenClawConfig } from "../../config/config.js";
|
||||
import type { ConversationRef } from "../../infra/outbound/session-binding-service.js";
|
||||
import type {
|
||||
ConfiguredBindingRecordResolution,
|
||||
ConfiguredBindingResolution,
|
||||
} from "./binding-types.js";
|
||||
import {
|
||||
countCompiledBindingRegistry,
|
||||
primeCompiledBindingRegistry,
|
||||
resolveCompiledBindingRegistry,
|
||||
} from "./configured-binding-compiler.js";
|
||||
import {
|
||||
materializeConfiguredBindingRecord,
|
||||
resolveMatchingConfiguredBinding,
|
||||
toConfiguredBindingConversationRef,
|
||||
} from "./configured-binding-match.js";
|
||||
import { resolveConfiguredBindingRecordBySessionKeyFromRegistry } from "./configured-binding-session-lookup.js";
|
||||
|
||||
export function primeConfiguredBindingRegistry(params: { cfg: OpenClawConfig }): {
|
||||
bindingCount: number;
|
||||
channelCount: number;
|
||||
} {
|
||||
return countCompiledBindingRegistry(primeCompiledBindingRegistry(params.cfg));
|
||||
}
|
||||
|
||||
export function resolveConfiguredBindingRecord(params: {
|
||||
cfg: OpenClawConfig;
|
||||
channel: string;
|
||||
accountId: string;
|
||||
conversationId: string;
|
||||
parentConversationId?: string;
|
||||
}): ConfiguredBindingRecordResolution | null {
|
||||
const conversation = toConfiguredBindingConversationRef({
|
||||
channel: params.channel,
|
||||
accountId: params.accountId,
|
||||
conversationId: params.conversationId,
|
||||
parentConversationId: params.parentConversationId,
|
||||
});
|
||||
if (!conversation) {
|
||||
return null;
|
||||
}
|
||||
return resolveConfiguredBindingRecordForConversation({
|
||||
cfg: params.cfg,
|
||||
conversation,
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveConfiguredBindingRecordForConversation(params: {
|
||||
cfg: OpenClawConfig;
|
||||
conversation: ConversationRef;
|
||||
}): ConfiguredBindingRecordResolution | null {
|
||||
const conversation = toConfiguredBindingConversationRef(params.conversation);
|
||||
if (!conversation) {
|
||||
return null;
|
||||
}
|
||||
const registry = resolveCompiledBindingRegistry(params.cfg);
|
||||
const rules = registry.rulesByChannel.get(conversation.channel);
|
||||
if (!rules || rules.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const resolved = resolveMatchingConfiguredBinding({
|
||||
rules,
|
||||
conversation,
|
||||
});
|
||||
if (!resolved) {
|
||||
return null;
|
||||
}
|
||||
return materializeConfiguredBindingRecord({
|
||||
rule: resolved.rule,
|
||||
accountId: conversation.accountId,
|
||||
conversation: resolved.match,
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveConfiguredBinding(params: {
|
||||
cfg: OpenClawConfig;
|
||||
conversation: ConversationRef;
|
||||
}): ConfiguredBindingResolution | null {
|
||||
const conversation = toConfiguredBindingConversationRef(params.conversation);
|
||||
if (!conversation) {
|
||||
return null;
|
||||
}
|
||||
const registry = resolveCompiledBindingRegistry(params.cfg);
|
||||
const rules = registry.rulesByChannel.get(conversation.channel);
|
||||
if (!rules || rules.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const resolved = resolveMatchingConfiguredBinding({
|
||||
rules,
|
||||
conversation,
|
||||
});
|
||||
if (!resolved) {
|
||||
return null;
|
||||
}
|
||||
const materializedTarget = materializeConfiguredBindingRecord({
|
||||
rule: resolved.rule,
|
||||
accountId: conversation.accountId,
|
||||
conversation: resolved.match,
|
||||
});
|
||||
return {
|
||||
conversation,
|
||||
compiledBinding: resolved.rule,
|
||||
match: resolved.match,
|
||||
...materializedTarget,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveConfiguredBindingRecordBySessionKey(params: {
|
||||
cfg: OpenClawConfig;
|
||||
sessionKey: string;
|
||||
}): ConfiguredBindingRecordResolution | null {
|
||||
return resolveConfiguredBindingRecordBySessionKeyFromRegistry({
|
||||
registry: resolveCompiledBindingRegistry(params.cfg),
|
||||
sessionKey: params.sessionKey,
|
||||
});
|
||||
}
|
||||
@ -0,0 +1,74 @@
|
||||
import type { ConfiguredBindingRecordResolution } from "./binding-types.js";
|
||||
import type { CompiledConfiguredBindingRegistry } from "./configured-binding-compiler.js";
|
||||
import { listConfiguredBindingConsumers } from "./configured-binding-consumers.js";
|
||||
import {
|
||||
materializeConfiguredBindingRecord,
|
||||
resolveAccountMatchPriority,
|
||||
resolveCompiledBindingChannel,
|
||||
} from "./configured-binding-match.js";
|
||||
|
||||
export function resolveConfiguredBindingRecordBySessionKeyFromRegistry(params: {
|
||||
registry: CompiledConfiguredBindingRegistry;
|
||||
sessionKey: string;
|
||||
}): ConfiguredBindingRecordResolution | null {
|
||||
const sessionKey = params.sessionKey.trim();
|
||||
if (!sessionKey) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const consumer of listConfiguredBindingConsumers()) {
|
||||
const parsed = consumer.parseSessionKey?.({ sessionKey });
|
||||
if (!parsed) {
|
||||
continue;
|
||||
}
|
||||
const channel = resolveCompiledBindingChannel(parsed.channel);
|
||||
if (!channel) {
|
||||
continue;
|
||||
}
|
||||
const rules = params.registry.rulesByChannel.get(channel);
|
||||
if (!rules || rules.length === 0) {
|
||||
continue;
|
||||
}
|
||||
let wildcardMatch: ConfiguredBindingRecordResolution | null = null;
|
||||
let exactMatch: ConfiguredBindingRecordResolution | null = null;
|
||||
for (const rule of rules) {
|
||||
if (rule.targetFactory.driverId !== consumer.id) {
|
||||
continue;
|
||||
}
|
||||
const accountMatchPriority = resolveAccountMatchPriority(
|
||||
rule.accountPattern,
|
||||
parsed.accountId,
|
||||
);
|
||||
if (accountMatchPriority === 0) {
|
||||
continue;
|
||||
}
|
||||
const materializedTarget = materializeConfiguredBindingRecord({
|
||||
rule,
|
||||
accountId: parsed.accountId,
|
||||
conversation: rule.target,
|
||||
});
|
||||
const matchesSessionKey =
|
||||
consumer.matchesSessionKey?.({
|
||||
sessionKey,
|
||||
compiledBinding: rule,
|
||||
accountId: parsed.accountId,
|
||||
materializedTarget,
|
||||
}) ?? materializedTarget.record.targetSessionKey === sessionKey;
|
||||
if (matchesSessionKey) {
|
||||
if (accountMatchPriority === 2) {
|
||||
exactMatch = materializedTarget;
|
||||
break;
|
||||
}
|
||||
wildcardMatch = materializedTarget;
|
||||
}
|
||||
}
|
||||
if (exactMatch) {
|
||||
return exactMatch;
|
||||
}
|
||||
if (wildcardMatch) {
|
||||
return wildcardMatch;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@ -0,0 +1,13 @@
|
||||
import { acpStatefulBindingTargetDriver } from "./acp-stateful-target-driver.js";
|
||||
import {
|
||||
registerStatefulBindingTargetDriver,
|
||||
unregisterStatefulBindingTargetDriver,
|
||||
} from "./stateful-target-drivers.js";
|
||||
|
||||
export function ensureStatefulTargetBuiltinsRegistered(): void {
|
||||
registerStatefulBindingTargetDriver(acpStatefulBindingTargetDriver);
|
||||
}
|
||||
|
||||
export function resetStatefulTargetBuiltinsForTesting(): void {
|
||||
unregisterStatefulBindingTargetDriver(acpStatefulBindingTargetDriver.id);
|
||||
}
|
||||
@ -0,0 +1,89 @@
|
||||
import type { OpenClawConfig } from "../../config/config.js";
|
||||
import type {
|
||||
ConfiguredBindingResolution,
|
||||
StatefulBindingTargetDescriptor,
|
||||
} from "./binding-types.js";
|
||||
|
||||
export type StatefulBindingTargetReadyResult = { ok: true } | { ok: false; error: string };
|
||||
export type StatefulBindingTargetSessionResult =
|
||||
| { ok: true; sessionKey: string }
|
||||
| { ok: false; sessionKey: string; error: string };
|
||||
export type StatefulBindingTargetResetResult =
|
||||
| { ok: true }
|
||||
| { ok: false; skipped?: boolean; error?: string };
|
||||
|
||||
export type StatefulBindingTargetDriver = {
|
||||
id: string;
|
||||
ensureReady: (params: {
|
||||
cfg: OpenClawConfig;
|
||||
bindingResolution: ConfiguredBindingResolution;
|
||||
}) => Promise<StatefulBindingTargetReadyResult>;
|
||||
ensureSession: (params: {
|
||||
cfg: OpenClawConfig;
|
||||
bindingResolution: ConfiguredBindingResolution;
|
||||
}) => Promise<StatefulBindingTargetSessionResult>;
|
||||
resolveTargetBySessionKey?: (params: {
|
||||
cfg: OpenClawConfig;
|
||||
sessionKey: string;
|
||||
}) => StatefulBindingTargetDescriptor | null;
|
||||
resetInPlace?: (params: {
|
||||
cfg: OpenClawConfig;
|
||||
sessionKey: string;
|
||||
bindingTarget: StatefulBindingTargetDescriptor;
|
||||
reason: "new" | "reset";
|
||||
}) => Promise<StatefulBindingTargetResetResult>;
|
||||
};
|
||||
|
||||
const registeredStatefulBindingTargetDrivers = new Map<string, StatefulBindingTargetDriver>();
|
||||
|
||||
function listStatefulBindingTargetDrivers(): StatefulBindingTargetDriver[] {
|
||||
return [...registeredStatefulBindingTargetDrivers.values()];
|
||||
}
|
||||
|
||||
export function registerStatefulBindingTargetDriver(driver: StatefulBindingTargetDriver): void {
|
||||
const id = driver.id.trim();
|
||||
if (!id) {
|
||||
throw new Error("Stateful binding target driver id is required");
|
||||
}
|
||||
const normalized = { ...driver, id };
|
||||
const existing = registeredStatefulBindingTargetDrivers.get(id);
|
||||
if (existing) {
|
||||
return;
|
||||
}
|
||||
registeredStatefulBindingTargetDrivers.set(id, normalized);
|
||||
}
|
||||
|
||||
export function unregisterStatefulBindingTargetDriver(id: string): void {
|
||||
registeredStatefulBindingTargetDrivers.delete(id.trim());
|
||||
}
|
||||
|
||||
export function getStatefulBindingTargetDriver(id: string): StatefulBindingTargetDriver | null {
|
||||
const normalizedId = id.trim();
|
||||
if (!normalizedId) {
|
||||
return null;
|
||||
}
|
||||
return registeredStatefulBindingTargetDrivers.get(normalizedId) ?? null;
|
||||
}
|
||||
|
||||
export function resolveStatefulBindingTargetBySessionKey(params: {
|
||||
cfg: OpenClawConfig;
|
||||
sessionKey: string;
|
||||
}): { driver: StatefulBindingTargetDriver; bindingTarget: StatefulBindingTargetDescriptor } | null {
|
||||
const sessionKey = params.sessionKey.trim();
|
||||
if (!sessionKey) {
|
||||
return null;
|
||||
}
|
||||
for (const driver of listStatefulBindingTargetDrivers()) {
|
||||
const bindingTarget = driver.resolveTargetBySessionKey?.({
|
||||
cfg: params.cfg,
|
||||
sessionKey,
|
||||
});
|
||||
if (bindingTarget) {
|
||||
return {
|
||||
driver,
|
||||
bindingTarget,
|
||||
};
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@ -0,0 +1,93 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
resolvePreferredNodePath: vi.fn(),
|
||||
resolveNodeProgramArguments: vi.fn(),
|
||||
resolveSystemNodeInfo: vi.fn(),
|
||||
renderSystemNodeWarning: vi.fn(),
|
||||
buildNodeServiceEnvironment: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../daemon/runtime-paths.js", () => ({
|
||||
resolvePreferredNodePath: mocks.resolvePreferredNodePath,
|
||||
resolveSystemNodeInfo: mocks.resolveSystemNodeInfo,
|
||||
renderSystemNodeWarning: mocks.renderSystemNodeWarning,
|
||||
}));
|
||||
|
||||
vi.mock("../daemon/program-args.js", () => ({
|
||||
resolveNodeProgramArguments: mocks.resolveNodeProgramArguments,
|
||||
}));
|
||||
|
||||
vi.mock("../daemon/service-env.js", () => ({
|
||||
buildNodeServiceEnvironment: mocks.buildNodeServiceEnvironment,
|
||||
}));
|
||||
|
||||
import { buildNodeInstallPlan } from "./node-daemon-install-helpers.js";
|
||||
|
||||
afterEach(() => {
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
describe("buildNodeInstallPlan", () => {
|
||||
it("passes the selected node bin directory into the node service environment", async () => {
|
||||
mocks.resolveNodeProgramArguments.mockResolvedValue({
|
||||
programArguments: ["node", "node-host"],
|
||||
workingDirectory: "/Users/me",
|
||||
});
|
||||
mocks.resolveSystemNodeInfo.mockResolvedValue({
|
||||
path: "/opt/node/bin/node",
|
||||
version: "22.0.0",
|
||||
supported: true,
|
||||
});
|
||||
mocks.renderSystemNodeWarning.mockReturnValue(undefined);
|
||||
mocks.buildNodeServiceEnvironment.mockReturnValue({
|
||||
OPENCLAW_SERVICE_VERSION: "2026.3.14",
|
||||
});
|
||||
|
||||
const plan = await buildNodeInstallPlan({
|
||||
env: {},
|
||||
host: "127.0.0.1",
|
||||
port: 18789,
|
||||
runtime: "node",
|
||||
nodePath: "/custom/node/bin/node",
|
||||
});
|
||||
|
||||
expect(plan.environment).toEqual({
|
||||
OPENCLAW_SERVICE_VERSION: "2026.3.14",
|
||||
});
|
||||
expect(mocks.resolvePreferredNodePath).not.toHaveBeenCalled();
|
||||
expect(mocks.buildNodeServiceEnvironment).toHaveBeenCalledWith({
|
||||
env: {},
|
||||
extraPathDirs: ["/custom/node/bin"],
|
||||
});
|
||||
});
|
||||
|
||||
it("does not prepend '.' when nodePath is a bare executable name", async () => {
|
||||
mocks.resolveNodeProgramArguments.mockResolvedValue({
|
||||
programArguments: ["node", "node-host"],
|
||||
workingDirectory: "/Users/me",
|
||||
});
|
||||
mocks.resolveSystemNodeInfo.mockResolvedValue({
|
||||
path: "/usr/bin/node",
|
||||
version: "22.0.0",
|
||||
supported: true,
|
||||
});
|
||||
mocks.renderSystemNodeWarning.mockReturnValue(undefined);
|
||||
mocks.buildNodeServiceEnvironment.mockReturnValue({
|
||||
OPENCLAW_SERVICE_VERSION: "2026.3.14",
|
||||
});
|
||||
|
||||
await buildNodeInstallPlan({
|
||||
env: {},
|
||||
host: "127.0.0.1",
|
||||
port: 18789,
|
||||
runtime: "node",
|
||||
nodePath: "node",
|
||||
});
|
||||
|
||||
expect(mocks.buildNodeServiceEnvironment).toHaveBeenCalledWith({
|
||||
env: {},
|
||||
extraPathDirs: undefined,
|
||||
});
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue