Skip to content

Commit a901d33

Browse files
authored
fix(skills): share the foreground prompt prefix with the experience review (#130013)
The detached Skill Workshop experience review rebuilt its system prompt and tool catalog from a different context than the foreground turn, so every review missed the prompt cache. Native harnesses (embedded, Codex, Copilot) now hand the review the same foreground prompt context via buildEmbeddedForegroundPromptContext; the review reuses the foreground prefix and gates execution to skill_workshop while keeping the catalog identical. Reviews without a foreground prompt (CLI hook contexts) are skipped.
1 parent a674615 commit a901d33

20 files changed

Lines changed: 646 additions & 171 deletions

‎docs/plugins/sdk-agent-harness.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,14 @@ side effects finish. Both helpers accept the same `{ event, ctx }` payload as
371371
`runAgentHarnessAgentEndHook(...)`; their failures do not alter the completed
372372
attempt result.
373373

374+
Pass `ctx.foregroundPromptContext` built with
375+
`buildEmbeddedForegroundPromptContext(params, agentDir)` from the same
376+
`EmbeddedRunAttemptParams` the attempt ran with. The detached Skill Workshop
377+
experience review rebuilds its system prompt and tool catalog from that
378+
context, so the review shares the foreground turn's prompt-cache prefix.
379+
Omit it only for runs that have no foreground prompt, such as CLI hook
380+
contexts; the review is skipped for those.
381+
374382
### User input and tool surfaces
375383

376384
Native harnesses that expose a runtime-level user-input request should use the

‎extensions/codex/src/app-server/run-attempt-finalize.ts‎

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import {
2+
buildEmbeddedForegroundPromptContext,
23
embeddedAgentLog,
34
formatErrorMessage,
45
runAgentHarnessLlmOutputHook,
@@ -67,6 +68,7 @@ export async function finalizeCodexAttempt(
6768
sessionAgentId,
6869
contextSessionKey,
6970
effectiveCwd,
71+
agentDir,
7072
attemptStartedAt,
7173
startupAuthProfileId,
7274
} = connection;
@@ -393,20 +395,11 @@ export async function finalizeCodexAttempt(
393395
attemptTools.toolBridge.availableSpecs,
394396
).some((tool) => tool.name === "skill_workshop"),
395397
compacted: (result.compactionCount ?? 0) > 0,
396-
messageChannel: params.messageChannel,
397-
messageProvider: params.messageProvider,
398-
chatType: params.chatType,
399-
agentAccountId: params.agentAccountId,
400-
groupId: params.groupId,
401-
groupChannel: params.groupChannel,
402-
groupSpace: params.groupSpace,
403-
memberRoleIds: params.memberRoleIds,
404-
spawnedBy: params.spawnedBy,
405398
senderId: params.senderId ?? undefined,
406-
senderName: params.senderName,
407-
senderUsername: params.senderUsername,
408-
senderE164: params.senderE164,
409-
senderIsOwner: params.senderIsOwner,
399+
foregroundPromptContext: buildEmbeddedForegroundPromptContext(
400+
{ ...params, agentId: sessionAgentId },
401+
agentDir,
402+
),
410403
},
411404
hookRunner,
412405
});
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Codex tests cover the agent-end context handed to OpenClaw side effects.
2+
import path from "node:path";
3+
import * as agentHarnessRuntime from "openclaw/plugin-sdk/agent-harness-runtime";
4+
import { describe, expect, it, vi } from "vitest";
5+
import {
6+
createParams,
7+
createStartedThreadHarness,
8+
runCodexAppServerAttempt,
9+
setupRunAttemptTestHooks,
10+
tempDir,
11+
} from "./run-attempt-test-harness.js";
12+
13+
setupRunAttemptTestHooks();
14+
15+
describe("runCodexAppServerAttempt agent-end context", () => {
16+
it("hands the foreground prompt context to agent-end side effects", async () => {
17+
const sessionFile = path.join(tempDir, "agent-end-context.jsonl");
18+
const workspaceDir = path.join(tempDir, "agent-end-context-workspace");
19+
const harness = createStartedThreadHarness();
20+
const runAgentEndSideEffects = vi.spyOn(agentHarnessRuntime, "runAgentEndSideEffects");
21+
const params = createParams(sessionFile, workspaceDir);
22+
params.messageChannel = "discord";
23+
params.memberRoleIds = ["maintainer-role"];
24+
25+
const run = runCodexAppServerAttempt(params);
26+
await harness.waitForMethod("turn/start");
27+
await harness.completeTurn({ threadId: "thread-1", turnId: "turn-1" });
28+
await run;
29+
30+
const ctx = runAgentEndSideEffects.mock.calls.at(-1)?.[0]?.ctx;
31+
expect(ctx?.foregroundPromptContext?.memberRoleIds).toEqual(["maintainer-role"]);
32+
expect(typeof ctx?.foregroundPromptContext?.agentDir).toBe("string");
33+
});
34+
});

‎extensions/copilot/src/attempt-prepare.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@ import fsp from "node:fs/promises";
22
import type { SandboxContext } from "openclaw/plugin-sdk/agent-harness-runtime";
33
import {
44
buildAgentHookContextChannelFields,
5+
buildEmbeddedForegroundPromptContext,
56
isHostScopedAgentToolActive,
7+
resolveAgentDir,
68
resolveSandboxContext as defaultResolveSandboxContext,
79
resolveSessionAgentIds,
810
} from "openclaw/plugin-sdk/agent-harness-runtime";
@@ -89,6 +91,10 @@ export function prepareCopilotAttemptContext(
8991
modelProviderId: modelRef.provider,
9092
modelId: modelRef.id,
9193
trigger: input.trigger,
94+
foregroundPromptContext: buildEmbeddedForegroundPromptContext(
95+
{ ...input, agentId: sessionAgentId },
96+
input.agentDir ?? resolveAgentDir(input.config ?? {}, sessionAgentId),
97+
),
9298
...(input.config ? { config: input.config } : {}),
9399
...hookContextWindowFields,
94100
...buildAgentHookContextChannelFields(input),

‎extensions/copilot/src/attempt.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { tmpdir } from "node:os";
44
import path from "node:path";
55
import type { CopilotClient, Tool as SdkTool } from "@github/copilot-sdk";
66
import { expectDefined } from "@openclaw/normalization-core";
7+
import * as agentHarnessRuntime from "openclaw/plugin-sdk/agent-harness-runtime";
78
import {
89
abortAgentHarnessRun,
910
applyEmbeddedAttemptToolsAllow,
@@ -567,6 +568,20 @@ describe("runCopilotAttempt", () => {
567568
expect(getSdkSessionId(result)).toBe("sess-1");
568569
});
569570

571+
it("hands the foreground prompt context to agent-end side effects", async () => {
572+
const runAgentEndSideEffects = vi.spyOn(agentHarnessRuntime, "runAgentEndSideEffects");
573+
const params = makeParams({
574+
memberRoleIds: ["maintainer-role"],
575+
messageChannel: "discord",
576+
});
577+
578+
await runCopilotAttempt(params, { pool: makeFakePool(makeFakeSdk()) });
579+
580+
const ctx = runAgentEndSideEffects.mock.calls.at(-1)?.[0]?.ctx;
581+
expect(ctx?.foregroundPromptContext?.memberRoleIds).toEqual(["maintainer-role"]);
582+
expect(ctx?.foregroundPromptContext?.agentDir).toBe(params.agentDir);
583+
});
584+
570585
it("retains the host terminal error after an unrelated successful tool", async () => {
571586
const terminalError = {
572587
error: "delivery failed",

‎scripts/plugin-sdk-surface-report.mts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -312,7 +312,8 @@ export function readPluginSdkSurfaceBudgets(env: NodeJS.ProcessEnv = process.env
312312
// +2: conversation-binding inspection result and runtime inspector.
313313
// +2: restore shipped channel setup helpers until stable packages migrate.
314314
// +1: canonical untrusted audio-transcript formatter for channel plugins.
315-
4340,
315+
// +2: embedded foreground prompt context builder and its public context type.
316+
4342,
316317
env,
317318
),
318319
publicFunctionExports: readPluginSdkSurfaceBudgetEnv(
@@ -404,7 +405,8 @@ export function readPluginSdkSurfaceBudgets(env: NodeJS.ProcessEnv = process.env
404405
// +1: read-only authoritative conversation-binding inspector.
405406
// +2: restore shipped channel setup helpers until stable packages migrate.
406407
// +1: canonical untrusted audio-transcript formatter for channel plugins.
407-
2581,
408+
// +1: embedded foreground prompt context builder.
409+
2582,
408410
env,
409411
),
410412
publicDeprecatedExports: readPluginSdkSurfaceBudgetEnv(

‎src/agents/embedded-agent-runner/run/agent-end-context.ts‎

Lines changed: 93 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,101 @@ import {
33
buildAgentHookContextIdentityFields,
44
} from "../../../plugins/hook-agent-context.js";
55
import type { runAgentEndSideEffects } from "../../harness/agent-end-side-effects.js";
6+
import type { EmbeddedForegroundPromptContext } from "./params.js";
67
import type { EmbeddedRunAttemptParams } from "./types.js";
78

8-
type AgentEndContext = Parameters<typeof runAgentEndSideEffects>[0]["ctx"] &
9-
Pick<EmbeddedRunAttemptParams, "reasoningLevel">;
9+
type AgentEndContext = Parameters<typeof runAgentEndSideEffects>[0]["ctx"] & {
10+
foregroundPromptContext: EmbeddedForegroundPromptContext;
11+
};
12+
13+
type EmbeddedForegroundPromptContextRun = Pick<
14+
EmbeddedRunAttemptParams,
15+
Exclude<keyof EmbeddedForegroundPromptContext, "agentDir" | "agentId" | "cronCreatorCallerOrigin">
16+
> &
17+
Pick<EmbeddedRunAttemptParams, "cronCreatorAuthorityCapability" | "sessionId" | "sessionKey"> & {
18+
agentId: string;
19+
};
20+
21+
export function buildEmbeddedForegroundPromptContext(
22+
run: EmbeddedForegroundPromptContextRun,
23+
agentDir: string,
24+
): EmbeddedForegroundPromptContext {
25+
const callerOrigin = run.cronCreatorAuthorityCapability?.callerOrigin;
26+
return {
27+
agentId: run.agentId,
28+
agentDir,
29+
workspaceDir: run.workspaceDir,
30+
cwd: run.cwd,
31+
sandboxSessionKey: run.sandboxSessionKey ?? run.sessionKey ?? run.sessionId,
32+
promptCacheKey: run.promptCacheKey,
33+
reasoningLevel: run.reasoningLevel,
34+
messageChannel: run.messageChannel,
35+
messageProvider: run.messageProvider,
36+
clientCaps: run.clientCaps,
37+
toolBindings: run.toolBindings,
38+
chatType: run.chatType,
39+
agentAccountId: run.agentAccountId,
40+
trigger: run.trigger,
41+
messageTo: run.messageTo,
42+
messageThreadId: run.messageThreadId,
43+
conversationToolPolicy: run.conversationToolPolicy,
44+
groupId: run.groupId,
45+
groupChannel: run.groupChannel,
46+
groupSpace: run.groupSpace,
47+
memberRoleIds: run.memberRoleIds,
48+
messageActionTurnCapability: run.messageActionTurnCapability,
49+
spawnedBy: run.spawnedBy,
50+
isCanonicalWorkspace: run.isCanonicalWorkspace,
51+
senderId: run.senderId,
52+
senderName: run.senderName,
53+
senderUsername: run.senderUsername,
54+
senderE164: run.senderE164,
55+
senderIsOwner: run.senderIsOwner,
56+
approvalReviewerDeviceId: run.approvalReviewerDeviceId,
57+
currentChannelId: run.currentChannelId,
58+
chatId: run.chatId,
59+
channelContext: run.channelContext,
60+
currentMessagingTarget: run.currentMessagingTarget,
61+
currentThreadTs: run.currentThreadTs,
62+
currentMessageId: run.currentMessageId,
63+
currentInboundAudio: run.currentInboundAudio,
64+
replyToMode: run.replyToMode,
65+
requireExplicitMessageTarget: run.requireExplicitMessageTarget,
66+
disableMessageTool: run.disableMessageTool,
67+
githubPublicationAvailable: run.githubPublicationAvailable,
68+
conversationRecall: run.conversationRecall,
69+
toolOverrides: run.toolOverrides,
70+
skillsSnapshot: run.skillsSnapshot,
71+
currentInboundEventKind: run.currentInboundEventKind,
72+
clientTools: run.clientTools,
73+
disableTools: run.disableTools,
74+
contextWindow: run.contextWindow,
75+
promptMode: run.promptMode,
76+
forceMessageTool: run.forceMessageTool,
77+
enableHeartbeatTool: run.enableHeartbeatTool,
78+
forceHeartbeatTool: run.forceHeartbeatTool,
79+
allowGatewaySubagentBinding: run.allowGatewaySubagentBinding,
80+
extraSystemPrompt: run.extraSystemPrompt,
81+
sourceReplyDeliveryMode: run.sourceReplyDeliveryMode,
82+
taskSuggestionDeliveryMode: run.taskSuggestionDeliveryMode,
83+
silentReplyPromptMode: run.silentReplyPromptMode,
84+
ownerNumbers: run.ownerNumbers,
85+
toolsAllow: run.toolsAllow,
86+
runtimePluginToolGrant: run.runtimePluginToolGrant,
87+
inputProvenance: run.inputProvenance,
88+
scheduledToolPolicy: run.scheduledToolPolicy,
89+
modelThinkingCapability: run.modelThinkingCapability,
90+
modelFallbacksOverride: run.modelFallbacksOverride,
91+
...(callerOrigin && callerOrigin.kind !== "unknown"
92+
? { cronCreatorCallerOrigin: callerOrigin }
93+
: {}),
94+
};
95+
}
1096

1197
export function buildEmbeddedAgentEndContext(params: {
1298
run: EmbeddedRunAttemptParams;
1399
agentId: string;
100+
agentDir: string;
14101
trace: AgentEndContext["trace"];
15102
skillWorkshopAvailable: boolean;
16103
compacted: boolean;
@@ -26,22 +113,13 @@ export function buildEmbeddedAgentEndContext(params: {
26113
modelProviderId: run.provider,
27114
modelId: run.modelId,
28115
modelContextWindowTokens: run.contextTokenBudget ?? run.model.contextWindow,
29-
reasoningLevel: run.reasoningLevel,
116+
foregroundPromptContext: buildEmbeddedForegroundPromptContext(
117+
{ ...run, agentId: params.agentId },
118+
params.agentDir,
119+
),
30120
authProfileId: run.authProfileId,
31121
skillWorkshopAvailable: params.skillWorkshopAvailable,
32122
compacted: params.compacted,
33-
messageChannel: run.messageChannel,
34-
chatType: run.chatType,
35-
agentAccountId: run.agentAccountId,
36-
groupId: run.groupId,
37-
groupChannel: run.groupChannel,
38-
groupSpace: run.groupSpace,
39-
memberRoleIds: run.memberRoleIds,
40-
spawnedBy: run.spawnedBy,
41-
senderName: run.senderName,
42-
senderUsername: run.senderUsername,
43-
senderE164: run.senderE164,
44-
senderIsOwner: run.senderIsOwner,
45123
trigger: run.trigger,
46124
...(run.config ? { config: run.config } : {}),
47125
...buildAgentHookContextChannelFields(run),

‎src/agents/embedded-agent-runner/run/attempt-finalize.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,7 @@ export async function completeEmbeddedAttemptAfterTurn(
394394
ctx: buildEmbeddedAgentEndContext({
395395
run: attempt,
396396
agentId: runtime.hookAgentId,
397+
agentDir: runtime.agentDir,
397398
trace: freezeDiagnosticTraceContext(runtime.diagnosticTrace),
398399
skillWorkshopAvailable: runtime.skillWorkshopAvailable,
399400
compacted: state.compactionOccurredThisAttempt,

‎src/agents/embedded-agent-runner/run/attempt-prompt-phase.test.ts‎

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,13 @@
1-
import { beforeEach, describe, expect, it, vi } from "vitest";
1+
import fs from "node:fs";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5+
import { upsertSessionEntryCore } from "../../../config/sessions/session-accessor.js";
6+
import { persistHeartbeatOutcome } from "../../../infra/heartbeat-outcome-store.js";
7+
import {
8+
closeOpenClawAgentDatabasesForTest,
9+
openOpenClawAgentDatabase,
10+
} from "../../../state/openclaw-agent-db.js";
211

312
const mocks = vi.hoisted(() => ({
413
applyPromptToolsAllow: vi.fn(),
@@ -78,6 +87,8 @@ type PromptErrorCall = {
7887
yieldMessage: string | null;
7988
};
8089

90+
const tempStateDirs: string[] = [];
91+
8192
function createFixture() {
8293
const order: string[] = [];
8394
const state: PromptPhaseState = {
@@ -304,7 +315,50 @@ beforeEach(() => {
304315
});
305316
});
306317

318+
afterEach(() => {
319+
closeOpenClawAgentDatabasesForTest();
320+
vi.unstubAllEnvs();
321+
for (const stateDir of tempStateDirs.splice(0)) {
322+
fs.rmSync(stateDir, { recursive: true, force: true });
323+
}
324+
});
325+
307326
describe("runEmbeddedAttemptPromptPhase", () => {
327+
it("does not claim heartbeat outcomes for detached user-triggered runs", async () => {
328+
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-prompt-phase-heartbeat-"));
329+
tempStateDirs.push(stateDir);
330+
vi.stubEnv("OPENCLAW_STATE_DIR", stateDir);
331+
await upsertSessionEntryCore(
332+
{ agentId: "main", env: process.env, sessionKey: "agent:main:main" },
333+
{ sessionId: "prompt-phase-heartbeat-test", updatedAt: 1 },
334+
);
335+
persistHeartbeatOutcome({
336+
agentId: "main",
337+
sessionKey: "agent:main:main",
338+
runSessionKey: "agent:main:main:heartbeat",
339+
response: { outcome: "progress", notify: false, summary: "Heartbeat context" },
340+
occurredAt: 1,
341+
env: process.env,
342+
});
343+
const fixture = createFixture();
344+
Object.assign(fixture.input.attempt, {
345+
sessionKey: "agent:main:main",
346+
sessionPersistence: "detached",
347+
trigger: "user",
348+
});
349+
350+
await runEmbeddedAttemptPromptPhase(fixture.input);
351+
352+
expect(mocks.preparePromptContext.mock.calls[0]?.[0]).not.toHaveProperty(
353+
"heartbeatOutcomeContext",
354+
);
355+
expect(
356+
openOpenClawAgentDatabase({ agentId: "main", env: process.env })
357+
.db.prepare("SELECT context_run_id, context_claimed_at FROM heartbeat_outcomes")
358+
.get(),
359+
).toEqual({ context_run_id: null, context_claimed_at: null });
360+
});
361+
308362
it("runs prompt work in phase order and publishes prompt outputs", async () => {
309363
const fixture = createFixture();
310364

‎src/agents/embedded-agent-runner/run/attempt-prompt-phase.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -235,8 +235,10 @@ export async function runEmbeddedAttemptPromptPhase(input: {
235235
input.lifecycle.setPromptCacheChangesForTurn(promptAssembly.promptCacheChangesForTurn);
236236

237237
try {
238+
const canClaimHeartbeatOutcome =
239+
attempt.trigger === "user" && attempt.sessionPersistence !== "detached";
238240
const heartbeatOutcomeContext =
239-
attempt.trigger === "user" && attempt.sessionKey
241+
canClaimHeartbeatOutcome && attempt.sessionKey
240242
? buildHeartbeatOutcomeContext(
241243
claimHeartbeatOutcomeForRun({
242244
agentId: input.context.sessionAgentId,

0 commit comments

Comments
 (0)