Repository navigation
fix: plugin tools disappear for agents with separate workspaces - #194876
saariuslystoned wants to merge 3 commits into
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesThis PR validates Gateway registry recovery using its discovery workspace while preserving the agent’s workspace for tool construction. Example: The research agent uses <root>/research-workspace while Gateway plugin discovery uses <root>/workspace, with x_search enabled and a dynamic model selected.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Regression provenancePossible regression — suspected (reviewed change). No predecessor PR is attributed. Merge readiness✅ Ready for maintainer review This PR fixes a current-main inventory defect with a focused change; no actionable defects remain in the reviewed patch. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe effective-tool resolver receives session, model, workspace, and policy facts, assembles tools from lifecycle-owned plugin registrations, and returns filtered inventory groups and availability diagnostics. flowchart TD
A[Gateway tools.effective request] --> B[Selected model context]
B --> C[Gateway registry recovery]
D[Captured discovery workspace] --> C
C --> E[Tool construction with agent workspace]
E --> F[Policy and compatibility filtering]
F --> G[Inventory and diagnostics]
Technical reviewBest possible solution: Merge the focused workspace comparison repair through the normal landing workflow. Do we have a high-confidence way to reproduce the issue? The fingerprint producer and current-main consumer show the workspace mismatch directly, corroborated by the contributor’s shipped-Gateway base/head trace; no target code was executed during this read-only review. Is this the best way to solve the issue? This is the smallest complete production repair: compare discovery identity using the existing registry owner’s workspace and retain the agent workspace for construction, without adding state, loaders, APIs, or policy. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against dec19a6acb83. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +4, Tests +177, Other +3. Total +184 across 3 files. Added test files: 0. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. Review metrics
LabelsLabel changes: No label changes. Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (1 earlier review cycle)
Reviewed November 8, 2026, 11:07 AM ET / 16:07 UTC (Revision 2). |
|
Shipped-Gateway proof for This supplies the missing end-to-end proof from the review: sanitized Setup. macOS arm64, Node 24.22.1, pnpm 12.15.0.
Result
The tools.effective, projected (agentId, profile, groups, the x_search access row)Artifact hashes (SHA-256). These are the full Scope: this covers inventory recovery only, as the PR states. It does not invoke X search or a model. Reproduce with the two files below: gw-lib.mts (isolated Gateway harness)// Shared isolated-Gateway harness for PR proof runs.
// Starts `node scripts/run-node.mjs gateway run` from a checkout with a throwaway
// HOME/state/config/TMPDIR/XDG tree, an ephemeral loopback port, auth none, and an
// allowlisted environment (no inherited OPENCLAW_* or provider keys).
import { spawn, type ChildProcess } from "node:child_process";
import { existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { connect, createServer } from "node:net";
import path from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
export type GatewayHandle = {
root: string;
port: number;
call: (method: string, params: unknown, timeoutMs?: number) => Promise<any>;
stop: () => Promise<{ code: number | null; signal: string | null }>;
};
// run-node keeps the checkout's dist lock for the Gateway's lifetime and leaves it on SIGTERM.
// Remove it only when its recorded owner process is gone (scratch checkout only).
export function clearDeadDistLock(checkout: string) {
const dir = path.join(checkout, ".artifacts", "dist-artifacts.lock");
const owner = path.join(dir, "owner.json");
if (!existsSync(owner)) return;
const pid = Number(JSON.parse(readFileSync(owner, "utf8")).pid);
try {
process.kill(pid, 0);
return; // still alive
} catch {}
rmSync(dir, { recursive: true, force: true });
}
export async function freePort(): Promise<number> {
return await new Promise((resolve) => {
const s = createServer();
s.listen(0, "127.0.0.1", () => {
const p = (s.address() as { port: number }).port;
s.close(() => resolve(p));
});
});
}
export function makeRoot(outDir: string) {
const root = path.join(outDir, "root");
for (const d of ["home", "state", "workspace", "tmp", "logs", "xdg-config", "xdg-data", "xdg-cache", "xdg-state"]) {
mkdirSync(path.join(root, d), { recursive: true });
}
return root;
}
export function isolatedEnv(root: string, configPath: string, extra: Record<string, string | undefined> = {}) {
const env: NodeJS.ProcessEnv = {
PATH: process.env.PATH,
LANG: "en_US.UTF-8",
HOME: path.join(root, "home"),
OPENCLAW_HOME: path.join(root, "home"),
OPENCLAW_STATE_DIR: path.join(root, "state"),
OPENCLAW_CONFIG_PATH: configPath,
TMPDIR: path.join(root, "tmp"),
XDG_CONFIG_HOME: path.join(root, "xdg-config"),
XDG_DATA_HOME: path.join(root, "xdg-data"),
XDG_CACHE_HOME: path.join(root, "xdg-cache"),
XDG_STATE_HOME: path.join(root, "xdg-state"),
OPENCLAW_SKIP_CHANNELS: "1",
OPENCLAW_SKIP_CRON: "1",
OPENCLAW_SKIP_BROWSER_CONTROL_SERVER: "1",
OPENCLAW_SKIP_CANVAS_HOST: "1",
OPENCLAW_SKIP_GMAIL_WATCHER: "1",
// Own service-coordination key: the default label is shared by every checkout on this Mac.
OPENCLAW_LAUNCHD_LABEL: "ai.openclaw.proofcloser",
};
for (const [k, v] of Object.entries(extra)) {
if (v === undefined) delete env[k];
else env[k] = v;
}
return env;
}
const portOpen = (port: number) =>
new Promise<boolean>((resolve) => {
const sock = connect(port, "127.0.0.1");
sock.once("connect", () => {
sock.destroy();
resolve(true);
});
sock.once("error", () => resolve(false));
});
export async function startGateway(params: {
checkout: string;
outDir: string;
root: string;
port: number;
config: Record<string, unknown>;
env?: Record<string, string | undefined>;
}): Promise<GatewayHandle> {
const { checkout, outDir, root, port } = params;
const configPath = path.join(root, "openclaw.json");
writeFileSync(configPath, `${JSON.stringify(params.config, null, 2)}\n`);
const env = isolatedEnv(root, configPath, params.env);
const args = ["scripts/run-node.mjs", "gateway", "run", "--port", String(port), "--bind", "loopback", "--auth", "none", "--tailscale", "off", "--allow-unconfigured"];
writeFileSync(
path.join(outDir, "gateway-command.txt"),
`cwd=<checkout>\nnode ${args.join(" ")}\nenv keys: ${Object.keys(env).toSorted().join(",")}\n`,
);
const gw: ChildProcess = spawn(process.execPath, args, {
cwd: checkout,
env,
detached: true,
stdio: ["ignore", openSync(path.join(outDir, "gateway.stdout.log"), "w"), openSync(path.join(outDir, "gateway.stderr.log"), "w")],
});
const exited = new Promise<{ code: number | null; signal: string | null }>((resolve) =>
gw.once("exit", (code, signal) => resolve({ code, signal })),
);
const deadline = Date.now() + 1_800_000;
while (!(await portOpen(port))) {
if (gw.exitCode !== null) throw new Error(`gateway exited early (${gw.exitCode}); see gateway.stderr.log`);
if (Date.now() > deadline) throw new Error("gateway not listening within 1800s");
await sleep(500);
}
const { GatewayClient, startGatewayClientWhenEventLoopReady } = await import(
path.join(checkout, "src/plugin-sdk/gateway-runtime.ts")
);
let helloResolve!: () => void;
const hello = new Promise<void>((r) => (helloResolve = r));
const client = new GatewayClient({
url: `ws://127.0.0.1:${port}`,
requestTimeoutMs: 180_000,
clientName: "gateway-client",
deviceIdentity: null,
mode: "backend",
scopes: ["operator.admin"],
onHelloOk: () => helloResolve(),
});
const readiness = await startGatewayClientWhenEventLoopReady(client, { timeoutMs: 180_000 });
if (!readiness.ready) throw new Error("gateway client readiness timeout");
await Promise.race([hello, sleep(180_000).then(() => { throw new Error("hello timeout"); })]);
return {
root,
port,
call: (method, p, timeoutMs = 180_000) => client.request(method, p, { timeoutMs }),
stop: async () => {
await client.stopAndWait?.().catch?.(() => {});
// Signal the run-node wrapper only: it forwards to the Gateway and releases its dist lock.
if (gw.exitCode === null && gw.pid) {
try { process.kill(gw.pid, "SIGTERM"); } catch {}
}
const timer = setTimeout(() => { try { if (gw.pid) process.kill(-gw.pid, "SIGKILL"); } catch {} }, 60_000);
const result = await exited;
clearTimeout(timer);
clearDeadDistLock(checkout);
return result;
},
};
}scenario-194876.mts// PR 194876: tools.effective for an agent whose workspace differs from the Gateway's
// discovery workspace, with a selected dynamic model (narrow selected-model lease).
// Usage: node --import <checkout>/scripts/tsx.mjs scenario-194876.mts <checkout> <outDir> <label>
import { mkdirSync, writeFileSync } from "node:fs";
import path from "node:path";
import { freePort, makeRoot, startGateway } from "./gw-lib.mts";
const [checkout, outDir, label] = process.argv.slice(2);
if (!checkout || !outDir || !label) throw new Error("usage: scenario-194876.mts <checkout> <outDir> <label>");
mkdirSync(outDir, { recursive: true });
const root = makeRoot(outDir);
const researchWorkspace = path.join(root, "research-workspace");
mkdirSync(researchWorkspace, { recursive: true });
writeFileSync(path.join(researchWorkspace, ".keep"), "synthetic Research workspace\n");
// Local provider plugin with a dynamic model, as in the PR's regression fixture.
const pluginDir = path.join(root, "plugins", "provider");
mkdirSync(pluginDir, { recursive: true });
const model = {
id: "chat-dynamic",
name: "chat-dynamic",
provider: "inventory-dynamic",
api: "openai-completions",
baseUrl: "http://127.0.0.1:9/v1", // never contacted: no inference in this scenario
reasoning: false,
input: ["text"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 128000,
maxTokens: 4096,
};
writeFileSync(
path.join(pluginDir, "index.cjs"),
`module.exports = {
id: "inventory-provider",
register(api) {
api.registerProvider({
id: "inventory-dynamic", label: "Inventory dynamic provider", auth: [],
async prepareDynamicModel(ctx) {
if (ctx.modelId === "chat-dynamic") return ${JSON.stringify(model)};
},
});
},
};
`,
);
writeFileSync(
path.join(pluginDir, "openclaw.plugin.json"),
JSON.stringify({ id: "inventory-provider", providers: ["inventory-dynamic"], configSchema: { type: "object", additionalProperties: false } }, null, 2),
);
const port = await freePort();
const config = {
meta: { migrations: { skillWorkshopPlugin: true } },
logging: { file: path.join(root, "logs", "openclaw-YYYY-MM-DD.log") },
gateway: { mode: "local", bind: "loopback", port, auth: { mode: "none" } },
agents: {
defaults: { model: "inventory-dynamic/chat-dynamic", workspace: path.join(root, "workspace"), systemAgent: { agentId: "main" } },
ownership: "explicit",
// main: same directory the Gateway discovers plugins from (equal control); research: separate.
entries: { main: { workspace: path.join(root, "workspace") }, research: { workspace: researchWorkspace } },
},
tools: { profile: "full", allow: ["x_search"] },
plugins: {
allow: ["inventory-provider", "xai"],
load: { paths: [path.join(pluginDir, "index.cjs")] },
slots: { memory: "none" },
entries: {
"inventory-provider": { enabled: true },
xai: { enabled: true, config: { xSearch: { enabled: true } } },
},
},
};
const gw = await startGateway({
checkout,
outDir,
root,
port,
config,
// Placeholder only; inventory never contacts xAI.
env: { XAI_API_KEY: "placeholder-not-a-real-key" },
});
const redact = (value: unknown) => JSON.parse(JSON.stringify(value).split(root).join("<root>"));
const toolIds = (inv: any) => (inv?.groups ?? []).flatMap((g: any) => (g.tools ?? []).map((t: any) => `${t.id}${t.pluginId ? `@${t.pluginId}` : ""}`));
const results: Record<string, unknown> = { label, port };
try {
for (const agentId of ["main", "research"]) {
const key = `agent:${agentId}:inventory-proof`;
const created = await gw.call("sessions.create", { agentId, key });
const inventory = await gw.call("tools.effective", { sessionKey: key, agentId });
writeFileSync(path.join(outDir, `tools-effective-${agentId}.json`), `${JSON.stringify(redact(inventory), null, 2)}\n`);
const ids = toolIds(inventory);
results[agentId] = {
sessionKey: key,
created: redact({ key: created?.key }),
toolCount: ids.length,
xSearch: ids.filter((id: string) => id.startsWith("x_search")),
xSearchAccess: inventory?.toolAccess?.tools?.find((t: any) => t.id === "x_search") ?? null,
};
}
const agents = await gw.call("agents.list", {}).catch((e: unknown) => ({ error: String(e) }));
results.agents = redact(
(agents?.agents ?? agents)?.map?.((a: any) => ({ id: a.id, workspace: a.workspace ?? a.workspaceDir })) ?? agents,
);
} finally {
results.gatewayExit = await gw.stop();
}
writeFileSync(path.join(outDir, "summary.json"), `${JSON.stringify(results, null, 2)}\n`);
console.log(JSON.stringify(results, null, 2));@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
Related: #194674 (merged; this is a separate workspace-recovery fix).
What Problem This Solves
Fixes enabled plugin tools, including
x_search, disappearing from effective tool inventory when an agent uses a workspace different from the Gateway's discovery workspace.User Impact
Agents with separate workspaces recover the Gateway's available plugin tools while retaining their existing tool and authentication policy. No configuration migration is needed. This PR covers inventory recovery; actual X invocation and citations remain pending on a separate Research execution failure.
Why This Change Was Made
The recovery guard compared a fingerprint captured for Gateway plugin discovery with one computed using the agent's execution workspace. It now compares the Gateway's discovery workspace while continuing to use the caller's config; tool creation still receives the agent's actual workspace.
Current-owner, manifest-identity, discovery-fingerprint, plugin-policy, narrow selected-model scope and retain/release guards remain intact. No new credential source or global fallback is introduced. Temporary Research timeout diagnostics are excluded.
The integration tests use real selected-model acquisition, the admitting Gateway registry and bundled XAI tool construction. A schema-only mock would not cross the discovery-workspace fingerprint guard that caused the empty inventory. Shared provider/owner setup and a three-row XAI table remove 96 lines from the initial tests while preserving all four cases. The remaining net growth is 177 regression-test lines. The separate allocation record grants exactly those 177 lines under the documented test-line policy; the shared scalar and all other allocations remain unchanged. This preserves existing base slack rather than consuming a moving shared allowance.
Evidence
60521f723188be7c91b768d424cafa1ef1e49453, real selected-model acquisition passes with equal workspaces and fails with distinct workspaces: expected['x_search'], actual[]. Both affected baseline files match source base963de16b208f24f398172db276fba482af98277c.5efaa44c7e70e9f1a5220a2c48b4a2735bc0b18b: direct OpenAI/Codex preview metadata, real selected-model acquisition with equal and distinct workspaces, and full Gateway recovery without widening the selected-model generation. Synthetic inherited XAI OAuth is present; no provider inference or X fetch occurs.963de16and CI's exact mergea921c919268147d320de3976c6fa03840c6290ffover base4f84bfd25e78aa35f6eb5fb17c5332d271fdfb29. The old CI failed by 51 lines because newer main reduced shared slack from 177 to 126; the allocation preserves both bases' existing slack.c3d95bd2ece101a370c85d6ae79818214bc7237b(base60521f7) changed the existing separate-workspace Research inventory from empty to exactly['x_search']. Its production repair is byte-identical, but that candidate also contains excluded diagnostics and is not exact-head PR proof. Its 59-test inventory suite is supporting evidence only.5efaa44found zero actionable defects. Current-head CI/review remain required; the native generation for that head failed before publishing a verdict and does not clear native review. No merge or release is requested.Focused validation commands
node scripts/run-vitest.mjs src/agents/tools-effective-inventory.gateway-plugin-tools.test.ts --maxWorkers=1 node scripts/run-tsgo.mjs -p tsconfig.core.json --incremental --tsBuildInfoFile .artifacts/tsgo-cache/core.tsbuildinfo node scripts/run-tsgo-core-test-shards.mts --changed-paths-json '["src/agents/tools-effective-inventory.gateway-plugin-tools.test.ts"]' --concurrency 1 node scripts/run-oxlint.mjs --threads 2 src/agents/tools-effective-inventory.ts src/agents/tools-effective-inventory.gateway-plugin-tools.test.ts node_modules/.bin/oxfmt --check src/agents/tools-effective-inventory.ts src/agents/tools-effective-inventory.gateway-plugin-tools.test.ts node --import ./scripts/tsx.mjs scripts/check-test-lines-ratchet.mts --base 963de16b208f24f398172db276fba482af98277c git diff --checkThe acquisition fixture uses a synthetic non-XAI dynamic model; it does not claim native OpenAI/Codex model discovery. Allocation checks also use task-owned index snapshots of the exact source and CI merge, with the real index and worktree untouched.