Skip to content

Commit d2cf05c

Browse files
authored
fix(agents): restore collector output and prepared harness execution (#131739)
* fix(agents): restore prepared collector and harness execution Carry collector output and noninteractive policy through shared tool preparation. Register Copilot during discovery, initialize selected direct credentials, retain canonical session IDs, and preserve failed-turn errors. Keep retained catalog callbacks bound to their owner generation rather than an expired publication transaction. Cover the owner boundaries with failing/passing regressions and real native, Codex, and Copilot Gateway runs, including credential recovery and same-process worker-policy reloads. Reuse the native auth test fixture instead of reloading the complete runner in every case. Fixes #131552 Fixes #131580 Fixes #131591 Fixes #131699 Fixes #131700 Fixes #131701 Thanks to @tmill313 for the original Codex collector report in #120077. * test(agents): keep collector proofs on owned boundaries Move real collector-tool and prepared-registry integration proof to core, retain independent plugin SDK handoff regressions, and select the host Copilot integration for plugin-only changes. Run the existing plugin-test core-import guard in changed-file checks so local validation catches the same boundary violation as CI. The replacement regressions fail against their pre-fix owners. All 505 focused tests, the exact import guard, and the changed-file gate pass. Independent review found no actionable P0-P2 findings. Runtime repair files are unchanged. * test(agents): load prepared harness through its public boundary Evaluate the real Copilot entrypoint through the existing public-surface loader and module-loader seam instead of importing plugin implementation into the core typegraph. Remove the synthetic entrypoint and registration global, while retaining real discovery and lazy-store assertions. Include the existing core tsgo graph boundary in changed-file checks and cover its ordinary and live-Docker routing paths. * test(mcp): seed canonical SQLite session history Use the installed candidate's public session APIs instead of creating legacy session files rejected by doctor-only startup. Preserve message IDs, parent ordering, delivery context, and canonical attachment metadata. Add a built-SDK fixture regression using real SQLite reads and startup validation. The full MCP client remains covered by the Docker CI lane. * test(gateway): preserve queued writes across RPC fixtures Stop clearing session writer queues before ordinary RPCs. Config fixtures still synchronize, while canonical writers retain their own cache updates. Prove queued-write ordering through a real connected Gateway against a raw WebSocket control, and dispose the custom test database before file removal. Preserve the underlying cause of the settlement timeout. That CI failure was not reproduced on the exact synthetic merge locally; the independent queue-reset defect is not being claimed as its established cause. * test(agents): keep harness fixture coverage on focused boundaries * test(imap): await committed watcher initialization
1 parent b05213c commit d2cf05c

39 files changed

Lines changed: 1548 additions & 366 deletions

‎extensions/codex/src/app-server/dynamic-tool-build.test.ts‎

Lines changed: 92 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -633,45 +633,57 @@ describe("Codex app-server dynamic tool build", () => {
633633
{
634634
mode: "guarded" as const,
635635
execMode: "ask" as const,
636+
command: "echo allowed",
637+
expected: { status: "completed" },
638+
},
639+
{
640+
mode: "guarded" as const,
641+
execMode: "ask" as const,
642+
command: "echo approval required",
636643
expected: { status: "failed", failureKind: "approval_required" },
637644
},
638-
{ mode: "full" as const, execMode: "full" as const, expected: { status: "completed" } },
639-
])("enforces the final $mode policy for an allowlisted Gateway command", async (testCase) => {
645+
{
646+
mode: "full" as const,
647+
execMode: "full" as const,
648+
command: "echo approval required",
649+
expected: { status: "completed" },
650+
},
651+
])("enforces $mode collector policy for $command", async (testCase) => {
640652
const workspaceDir = path.join(tempDir, `${testCase.mode}-allowlisted-workspace`);
641653
await fs.mkdir(workspaceDir, { recursive: true });
642654
const params = createParams(
643655
path.join(tempDir, `${testCase.mode}-allowlisted.jsonl`),
644656
workspaceDir,
645657
);
646658
params.disableTools = false;
659+
params.swarmCollector = true;
660+
params.pluginHarnessToolPolicyRestricted = true;
647661
params.permissionMode = testCase.mode;
648662
params.sessionRoot = workspaceDir;
649663
params.execOverrides = { host: "gateway", mode: testCase.execMode };
664+
// Guarded mode asks only on an allowlist miss; two arguments exceed this profile.
650665
params.config = {
651666
tools: { exec: { safeBins: ["echo"], safeBinProfiles: { echo: { maxPositional: 1 } } } },
652667
};
653668
params.runtimePlan = createCodexRuntimePlanFixture();
654669
setOpenClawCodingToolsFactoryForTests((options) =>
655-
createOpenClawCodingTools({
656-
...options,
657-
swarmCollector: true,
658-
wrapBeforeToolCallHook: false,
659-
}).filter((tool) => ["exec", "process"].includes(tool.name)),
670+
createOpenClawCodingTools(options).filter((tool) => ["exec", "process"].includes(tool.name)),
660671
);
661672

662673
const tools = await buildDynamicToolsForTest(params, workspaceDir, {
674+
nativeToolSurfaceEnabled: shouldEnableCodexAppServerNativeToolSurface(params),
663675
sessionPermissionPolicy: {
664676
mode: testCase.mode,
665677
root: workspaceDir,
666678
execMode: testCase.execMode,
667679
},
668680
});
669681
const gatewayExec = expectDefined(
670-
tools.find((tool) => tool.name === "gateway_exec"),
671-
`${testCase.mode} Gateway shell alias`,
682+
tools.find((tool) => tool.name === "exec"),
683+
`${testCase.mode} OpenClaw shell replacement`,
672684
);
673685
const result = await gatewayExec.execute(`${testCase.mode}-allowlisted`, {
674-
command: `echo ${testCase.mode}`,
686+
command: testCase.command,
675687
ask: "off",
676688
security: "full",
677689
});
@@ -850,6 +862,76 @@ describe("Codex app-server dynamic tool build", () => {
850862
expect(receivedOptions).toMatchObject({ taskSuggestionDeliveryMode: "gateway" });
851863
});
852864

865+
it.each([{ toolsAllow: undefined }, { toolsAllow: ["read"] }, { toolsAllow: [] }])(
866+
"preserves the collector handoff and dynamic tool through allowlist %j",
867+
async ({ toolsAllow }) => {
868+
const workspaceDir = path.join(tempDir, "workspace");
869+
const params = createParams(path.join(tempDir, "collector-session.jsonl"), workspaceDir);
870+
params.disableTools = false;
871+
params.runtimePlan = createCodexRuntimePlanFixture();
872+
params.toolsAllow = toolsAllow;
873+
params.swarmCollector = true;
874+
params.pluginHarnessToolPolicyRestricted = true;
875+
params.swarmOutputSchema = {
876+
type: "object",
877+
properties: { answer: { type: "string" } },
878+
required: ["answer"],
879+
};
880+
// An independent host result: the factory must not repair dropped attempt fields.
881+
const output = {
882+
...createRuntimeDynamicTool("structured_output"),
883+
catalogMode: "direct-only" as const,
884+
};
885+
const factory = vi.fn(() => [createRuntimeDynamicTool("read"), output]);
886+
setOpenClawCodingToolsFactoryForTests(factory);
887+
const tools = await buildDynamicToolsForTest(params, workspaceDir, {
888+
sandbox: null,
889+
nativeToolSurfaceEnabled: shouldEnableCodexAppServerNativeToolSurface(params),
890+
});
891+
892+
expect(factory).toHaveBeenCalledWith(
893+
expect.objectContaining({
894+
swarmCollector: true,
895+
swarmOutputSchema: params.swarmOutputSchema,
896+
...(toolsAllow ? { runtimeToolAllowlist: [...toolsAllow, "structured_output"] } : {}),
897+
}),
898+
);
899+
expect(shouldEnableCodexAppServerNativeToolSurface(params)).toBe(false);
900+
expect(tools.map((tool) => tool.name).toSorted()).toEqual(
901+
[...(toolsAllow ?? ["read"]), "structured_output"].toSorted(),
902+
);
903+
const bridge = createCodexDynamicToolBridge({
904+
tools,
905+
signal: new AbortController().signal,
906+
});
907+
const outputSpec = expectDefined(
908+
flattenCodexDynamicToolFunctions(bridge.specs).find(
909+
(tool) => tool.name === "structured_output",
910+
),
911+
"collector dynamic tool spec",
912+
);
913+
expect(outputSpec.deferLoading).not.toBe(true);
914+
const args = { result: { answer: "ok" } };
915+
const response = await bridge.handleToolCall({
916+
threadId: "collector-thread",
917+
turnId: "collector-turn",
918+
tool: "structured_output",
919+
callId: "collector-result",
920+
arguments: args,
921+
});
922+
expect(response).toMatchObject({
923+
success: true,
924+
contentItems: [{ type: "inputText", text: "structured_output done" }],
925+
});
926+
expect(output.execute).toHaveBeenCalledWith(
927+
"collector-result",
928+
args,
929+
expect.any(AbortSignal),
930+
undefined,
931+
);
932+
},
933+
);
934+
853935
it("preserves the host-provided OpenClaw tool through the Codex allowlist", async () => {
854936
const workspaceDir = path.join(tempDir, "workspace");
855937
const params = createParams(path.join(tempDir, "session.jsonl"), workspaceDir);

‎extensions/codex/src/app-server/dynamic-tool-build.ts‎

Lines changed: 10 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,10 @@ export async function buildDynamicTools(input: DynamicToolBuildParams) {
254254
const messagePolicyParams = input.ignoreDisableMessageTool
255255
? { ...params, disableMessageTool: false }
256256
: params;
257+
const toolRunContext = buildEmbeddedAttemptToolRunContext({
258+
...params,
259+
forceMessageTool: shouldForceMessageTool(messagePolicyParams),
260+
});
257261
if (params.disableTools) {
258262
input.onWebSearchPolicyResolved?.(false);
259263
return [];
@@ -291,7 +295,7 @@ export async function buildDynamicTools(input: DynamicToolBuildParams) {
291295
);
292296
const options: OpenClawCodingToolsOptions = {
293297
agentId: input.sessionAgentId,
294-
...buildEmbeddedAttemptToolRunContext(params),
298+
...toolRunContext,
295299
exec: {
296300
...params.execOverrides,
297301
...(input.sessionPermissionPolicy ? { mode: input.sessionPermissionPolicy.execMode } : {}),
@@ -508,8 +512,10 @@ export async function buildDynamicTools(input: DynamicToolBuildParams) {
508512
transientWebSearchRestriction &&
509513
webSearchPolicy.persistentAllowed),
510514
);
511-
const toolsAllow = includeForcedCodexDynamicToolAllow(params.toolsAllow, messagePolicyParams);
512-
const filteredTools = filterCodexDynamicToolsForAllowlist(visionFilteredTools, toolsAllow);
515+
const filteredTools = filterCodexDynamicToolsForAllowlist(
516+
visionFilteredTools,
517+
toolRunContext.runtimeToolAllowlist,
518+
);
513519
toolBuildStages.mark("allowlist-filter");
514520
const normalizedTools = normalizeAgentRuntimeTools({
515521
runtimePlan: input.ignoreRuntimePlan ? undefined : params.runtimePlan,
@@ -626,27 +632,6 @@ function addGatewayShellDynamicToolsIfAvailable(
626632
}
627633
return [...filteredTools, ...toolsToAppend];
628634
}
629-
/** Preserves delivery-critical tools when a narrow allowlist would otherwise hide them. */
630-
function includeForcedCodexDynamicToolAllow(
631-
toolsAllow: string[] | undefined,
632-
params: EmbeddedRunAttemptParams,
633-
): string[] | undefined {
634-
if (toolsAllow === undefined || hasWildcardCodexToolsAllow(toolsAllow)) {
635-
return toolsAllow;
636-
}
637-
const forcedToolNames = shouldForceMessageTool(params) ? ["message"] : [];
638-
if (forcedToolNames.length === 0) {
639-
return toolsAllow;
640-
}
641-
if (toolsAllow.length === 0) {
642-
return forcedToolNames;
643-
}
644-
const normalized = new Set(toolsAllow.map((name) => normalizeCodexDynamicToolName(name)));
645-
const missingToolNames = forcedToolNames.filter(
646-
(toolName) => !normalized.has(normalizeCodexDynamicToolName(toolName)),
647-
);
648-
return missingToolNames.length === 0 ? toolsAllow : [...toolsAllow, ...missingToolNames];
649-
}
650635
/** Decides whether Codex native code mode can own shell/file tools for this turn. */
651636
export function shouldEnableCodexAppServerNativeToolSurface(
652637
params: EmbeddedRunAttemptParams,
@@ -675,7 +660,7 @@ export function shouldEnableCodexAppServerNativeToolSurface(
675660
) {
676661
return false;
677662
}
678-
const toolsAllow = includeForcedCodexDynamicToolAllow(params.toolsAllow, params);
663+
const toolsAllow = params.toolsAllow;
679664
if (toolsAllow === undefined) {
680665
return canCodexAppServerNativeToolSurfaceHonorSandbox(sandbox, options);
681666
}

0 commit comments

Comments
 (0)