Skip to content

Commit 967696b

Browse files
VACIncroboclaw-bot
andauthored
fix(agents): restore system-agent delegation in channel turns (#128084)
* fix(agents): isolate probe runtime generation * test(qa): prove channel system-agent delegation --------- Co-authored-by: VACInc <[email protected]> Co-authored-by: RoboClaw <[email protected]>
1 parent f5553a8 commit 967696b

5 files changed

Lines changed: 196 additions & 1 deletion

File tree

‎extensions/qa-lab/src/providers/mock-openai/mock-openai-tooling.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,11 @@ export function buildQaToolSearchArgs(
298298
if (targetTool === "message") {
299299
return { action: "send", message: "runtime parity message fixture" };
300300
}
301+
if (targetTool === "openclaw") {
302+
return {
303+
message: "Reply exactly QA-SYSTEM-AGENT-DELEGATE-INFERENCE-OK. Do not call tools.",
304+
};
305+
}
301306
if (targetTool === "ask_user") {
302307
return {
303308
questions: [
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
title: System-agent delegation from a channel turn
2+
3+
scenario:
4+
id: system-agent-delegation-generation
5+
surface: channel
6+
coverage:
7+
primary:
8+
- agent-runtime.delegated-tool-access
9+
secondary:
10+
- channels.qa-channel-outbound
11+
objective: Verify a channel-scoped agent can complete first-use system-agent delegation while an admitted plugin generation is active.
12+
successCriteria:
13+
- A synthetic channel turn exposes and calls the real openclaw delegate tool once.
14+
- First-use inference verification completes through its isolated read-only runtime.
15+
- The delegate result contains the system-agent marker and no generation-guard failure.
16+
- The parent turn records a successful tool result and emits one visible channel reply.
17+
docsRefs:
18+
- docs/channels/qa-channel.md
19+
codeRefs:
20+
- src/agents/tools/openclaw-delegate-tool.ts
21+
- src/gateway/server-methods/system-agent.ts
22+
- src/system-agent/inference-fallback.ts
23+
- src/agents/embedded-agent-runner/run-orchestrator.ts
24+
execution:
25+
kind: flow
26+
summary: Exercise channel-to-system-agent delegation through an ephemeral Gateway and mock provider.
27+
config:
28+
requiredProviderMode: mock-openai
29+
requiredProvider: mock-openai
30+
conversationId: qa-system-agent-delegation
31+
promptSnippet: system agent delegation generation qa check
32+
prompt: "@openclaw tool search qa check target=openclaw. System agent delegation generation QA check. Call the openclaw tool exactly once, then reply exactly: QA-SYSTEM-AGENT-DELEGATE-OK."
33+
delegateReplyMarker: QA-SYSTEM-AGENT-DELEGATE-INFERENCE-OK
34+
expectedMarker: QA-SYSTEM-AGENT-DELEGATE-OK
35+
generationGuardError: prepared model runtime replaced the admitted plugin generation
36+
37+
flow:
38+
steps:
39+
- name: completes first-use system-agent delegation from a channel turn
40+
actions:
41+
- assert:
42+
expr: "env.providerMode === 'mock-openai'"
43+
message: this boundary scenario is mock-openai only
44+
- call: waitForGatewayHealthy
45+
args:
46+
- ref: env
47+
- 60000
48+
- call: waitForQaChannelReady
49+
args:
50+
- ref: env
51+
- 60000
52+
- call: reset
53+
- set: delivery
54+
value:
55+
expr: "transport.buildAgentDelivery({ target: `channel:${config.conversationId}` })"
56+
- set: sessionKey
57+
value:
58+
expr: "buildAgentSessionKey({ agentId: 'qa', channel: delivery.channel, accountId: transport.accountId, peer: { kind: 'group', id: delivery.replyTo }, dmScope: env.cfg.session?.dmScope, identityLinks: env.cfg.session?.identityLinks })"
59+
- set: requestCursorBefore
60+
value:
61+
expr: "(await fetchJson(`${env.mock.baseUrl}/debug/request-cursor`)).cursor"
62+
- sendInbound:
63+
conversation:
64+
id:
65+
expr: config.conversationId
66+
kind: channel
67+
title: QA System Agent Delegation
68+
senderId: alice
69+
senderName: Alice
70+
text:
71+
expr: config.prompt
72+
- call: waitForOutboundMessage
73+
saveAs: outbound
74+
args:
75+
- ref: state
76+
- lambda:
77+
params: [candidate]
78+
expr: "candidate.direction === 'outbound' && candidate.conversation.id === config.conversationId && candidate.conversation.kind === 'channel' && !candidate.threadId && String(candidate.text ?? '').includes(config.expectedMarker)"
79+
- expr: liveTurnTimeoutMs(env, 180000)
80+
- call: waitForCondition
81+
args:
82+
- lambda:
83+
async: true
84+
expr: "env.gateway.call('sessions.list', {}, { timeoutMs: 30000 }).then((result) => result.sessions?.find((session) => session.key === sessionKey && session.hasActiveRun === false))"
85+
- expr: liveTurnTimeoutMs(env, 180000)
86+
- 100
87+
- set: scenarioRequests
88+
value:
89+
expr: "(await fetchJson(`${env.mock.baseUrl}/debug/requests?after=${requestCursorBefore}`)).filter((request) => String(request.allInputText ?? '').toLowerCase().includes(config.promptSnippet))"
90+
- set: delegatePlan
91+
value:
92+
expr: "scenarioRequests.find((request) => request.plannedToolName === 'openclaw')"
93+
- set: delegateResult
94+
value:
95+
expr: "scenarioRequests.find((request) => request.toolOutputCallId === delegatePlan?.plannedToolCallId)"
96+
- assert:
97+
expr: "scenarioRequests.filter((request) => request.plannedToolName === 'openclaw').length === 1 && delegatePlan?.plannedToolArgs?.message === `Reply exactly ${config.delegateReplyMarker}. Do not call tools.`"
98+
message:
99+
expr: "`expected exactly one openclaw delegate plan, saw ${JSON.stringify(scenarioRequests.map((request) => ({ tool: request.plannedToolName ?? null, args: request.plannedToolArgs ?? null })))}`"
100+
- assert:
101+
expr: "String(delegateResult?.toolOutput ?? '').includes(config.delegateReplyMarker) && !String(delegateResult?.toolOutput ?? '').includes(config.generationGuardError)"
102+
message:
103+
expr: "`delegate did not cross first-use inference verification: ${String(delegateResult?.toolOutput ?? '')}`"
104+
- call: readSessionTranscriptSummary
105+
saveAs: transcript
106+
args:
107+
- ref: env
108+
- ref: sessionKey
109+
- assert:
110+
expr: "transcript.successfulToolCallCounts.openclaw === 1 && transcript.finalText.includes(config.expectedMarker)"
111+
message:
112+
expr: "`channel transcript lost the successful delegate result or final reply: ${JSON.stringify(transcript)}`"
113+
- set: matchingOutbound
114+
value:
115+
expr: "state.getSnapshot().messages.filter((message) => message.direction === 'outbound' && message.conversation.id === config.conversationId && message.conversation.kind === 'channel' && String(message.text ?? '').includes(config.expectedMarker))"
116+
- assert:
117+
expr: matchingOutbound.length === 1
118+
message:
119+
expr: "`expected one visible channel reply, saw ${matchingOutbound.length}`"
120+
detailsExpr: "JSON.stringify({ verdict: 'PASS', scenario: 'system-agent-delegation-generation', provider: env.providerMode, gateway: 'ephemeral-child', transport: transport.id, plannedDelegateCalls: scenarioRequests.filter((request) => request.plannedToolName === 'openclaw').length, successfulDelegateResults: transcript.successfulToolCallCounts.openclaw, delegateReplyMarkerPresent: String(delegateResult?.toolOutput ?? '').includes(config.delegateReplyMarker), generationGuardErrorPresent: String(delegateResult?.toolOutput ?? '').includes(config.generationGuardError), visibleChannelReplies: matchingOutbound.length }, null, 2)"

‎src/agents/embedded-agent-runner/run-orchestrator.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,8 +94,13 @@ export function runEmbeddedAgent(
9494
const lifecycleGeneration =
9595
internalParamsInput.lifecycleGeneration ??
9696
captureAgentRunLifecycleGeneration(internalParamsInput.runId);
97+
// Isolated probes acquire their own read-only runtime snapshot. Carrying the caller's
98+
// ambient generation makes the admission guard reject that independent snapshot.
9799
const pluginGeneration =
98-
internalParamsInput.pluginGeneration ?? getPreparedModelRuntimePluginGeneration();
100+
internalParamsInput.pluginGeneration ??
101+
(internalParamsInput.preparedModelRuntimeMode === "isolated-read-only"
102+
? undefined
103+
: getPreparedModelRuntimePluginGeneration());
99104
return withAgentRunLifecycleGeneration(lifecycleGeneration, () =>
100105
runEmbeddedAgentInternal({
101106
...internalParamsInput,

‎src/agents/embedded-agent-runner/run.overflow-compaction.harness.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1034,6 +1034,7 @@ export async function loadRunOverflowCompactionHarness(): Promise<{
10341034
vi.doMock("../prepared-model-runtime.js", () => ({
10351035
activateStandalonePreparedModelRuntime: vi.fn(async () => {}),
10361036
acquireAgentRunPreparedModelRuntime: mockedAcquireAgentRunPreparedModelRuntime,
1037+
acquireReadOnlyPreparedModelRuntime: mockedAcquireAgentRunPreparedModelRuntime,
10371038
prepareModelRuntimeSnapshot: vi.fn(async () => ({
10381039
createStores: () => ({ authStorage: {}, modelRegistry: {} }),
10391040
})),

‎src/agents/embedded-agent-runner/run.prepared-harness-source-delivery.integration.test.ts‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -578,6 +578,70 @@ describe("prepared harness source delivery", () => {
578578
expect(release).toHaveBeenCalledOnce();
579579
});
580580

581+
it("starts an isolated probe outside its caller's admitted generation", async () => {
582+
const { runEmbeddedAgent } = await loadRunOverflowCompactionHarness();
583+
const config = {};
584+
const workspaceDir = "/tmp/isolated-probe-workspace";
585+
const baseLease = await mockedAcquireAgentRunPreparedModelRuntime({
586+
agentId: "openclaw",
587+
agentDir: "/tmp/isolated-probe-agent",
588+
workspaceDir,
589+
});
590+
const admittedGeneration: PreparedModelRuntimePluginGeneration = {
591+
configuredCatalogEntries: [],
592+
inlineProviderModels: [],
593+
pluginMetadataSnapshot: {
594+
...baseLease.snapshot.metadataSnapshot,
595+
policyHash: "admitted",
596+
workspaceDir,
597+
},
598+
pluginRegistry: createEmptyPluginRegistry(),
599+
};
600+
const isolatedMetadataSnapshot = {
601+
...baseLease.snapshot.metadataSnapshot,
602+
policyHash: "isolated",
603+
workspaceDir,
604+
};
605+
const release = vi.fn();
606+
mockedAcquireAgentRunPreparedModelRuntime.mockClear();
607+
mockedAcquireAgentRunPreparedModelRuntime.mockResolvedValueOnce({
608+
...baseLease,
609+
snapshot: {
610+
...baseLease.snapshot,
611+
config,
612+
workspaceDir,
613+
metadataSnapshot: isolatedMetadataSnapshot,
614+
},
615+
release,
616+
});
617+
mockedBuildEmbeddedRunPayloads.mockReturnValue([{ text: "ok" }]);
618+
mockedRunEmbeddedAttempt.mockResolvedValueOnce(makeAttemptResult({ assistantTexts: ["ok"] }));
619+
useOpenAIPlatformAuthFixture();
620+
621+
const isolatedProbeParams: RunEmbeddedAgentInternalParams = {
622+
...overflowBaseRunParams,
623+
agentId: "openclaw",
624+
agentDir: "/tmp/isolated-probe-agent",
625+
config,
626+
provider: "openai",
627+
model: "gpt-5.4",
628+
preparedModelRuntimeMode: "isolated-read-only",
629+
runId: "isolated-probe-generation",
630+
sessionKey: undefined,
631+
workspaceDir,
632+
};
633+
const result = await withPreparedModelRuntimePluginGenerationScope(
634+
admittedGeneration,
635+
async () => await runEmbeddedAgent(isolatedProbeParams),
636+
);
637+
638+
expect(mockedAcquireAgentRunPreparedModelRuntime).toHaveBeenCalledWith(
639+
expect.objectContaining({ config, loadRuntimePlugins: true, workspaceDir }),
640+
);
641+
expect(result.payloads).toEqual([{ text: "ok" }]);
642+
expect(release).toHaveBeenCalledOnce();
643+
});
644+
581645
it.each([
582646
["agentHarnessId", { agentHarnessId: "codex" }],
583647
["agentHarnessRuntimeOverride", { agentHarnessRuntimeOverride: "codex" }],

0 commit comments

Comments
 (0)