From 58c4a92708e653d93db21aac1d934cdf9073cdd3 Mon Sep 17 00:00:00 2001 From: Tao Sun Date: Fri, 13 Nov 2026 14:53:50 +0800 Subject: [PATCH 1/2] Allow plugin settings with MXC enabled Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- desktop/renderer/src/i18n/en-US.ts | 3 +- desktop/renderer/src/i18n/zh-CN.ts | 2 +- desktop/src/config-write-policy.ts | 13 +- desktop/src/config-write-service.test.ts | 42 +++++ desktop/src/config-write-service.ts | 17 +- desktop/src/gateway-config-migrations.ts | 21 +++ desktop/src/main.ts | 65 ++++++-- desktop/src/model-config-application.test.ts | 105 +++++++++++- desktop/src/model-config-application.ts | 56 +++++-- desktop/src/search-config-application.ts | 14 +- .../src/windows-node-mxc-model-config.test.ts | 149 +++++++++++++++--- desktop/src/windows-node-mxc-model-config.ts | 46 ++++-- docs/experimental-windows-node-mxc.md | 4 + 13 files changed, 456 insertions(+), 81 deletions(-) create mode 100644 desktop/src/gateway-config-migrations.ts diff --git a/desktop/renderer/src/i18n/en-US.ts b/desktop/renderer/src/i18n/en-US.ts index baf2335..bbe6d12 100644 --- a/desktop/renderer/src/i18n/en-US.ts +++ b/desktop/renderer/src/i18n/en-US.ts @@ -1125,8 +1125,7 @@ export default { "perm.phoneSending": "Sending this approval to WeChat; the original timeout still applies.", "perm.phoneSent": "WeChat notified: reply 1 to allow once or 3 to deny. 2 is available only if the phone prompt offers it. Replies affect the current delivered prompt; a delayed reply can affect a newer prompt.", - "plugins.weixinMutationLocked": - "Changing the WeChat channel requires MXC to be off. Account changes require active containment.", + "plugins.weixinMutationLocked": "Wait for the current security settings change to finish.", "plugins.weixinLoginLocked": "Wait for containment or the current WeChat account change to finish.", "plugins.weixinMutationUnknown": diff --git a/desktop/renderer/src/i18n/zh-CN.ts b/desktop/renderer/src/i18n/zh-CN.ts index 2b51574..d3fe89b 100644 --- a/desktop/renderer/src/i18n/zh-CN.ts +++ b/desktop/renderer/src/i18n/zh-CN.ts @@ -1049,7 +1049,7 @@ export default { "perm.phoneSending": "正在向微信发送此审批;原超时期限仍然生效。", "perm.phoneSent": "已通知微信:回复 1 仅允许一次,3 拒绝;仅当手机提示提供 2 时才可使用。回复作用于当前已发送的审批,延迟回复可能影响更新的审批。", - "plugins.weixinMutationLocked": "更改微信频道需要关闭 MXC。账户操作需要隔离已就绪。", + "plugins.weixinMutationLocked": "请等待当前安全设置变更完成。", "plugins.weixinLoginLocked": "请等待隔离验证或当前微信账户操作完成。", "plugins.weixinMutationUnknown": "在确认主进程的 MXC 状态之前,微信配置保持锁定。", "perm.phoneCodeRequired": diff --git a/desktop/src/config-write-policy.ts b/desktop/src/config-write-policy.ts index 7036446..b32d8a1 100644 --- a/desktop/src/config-write-policy.ts +++ b/desktop/src/config-write-policy.ts @@ -1,6 +1,6 @@ import { isDeepStrictEqual } from "node:util"; import { hasConfiguredModel } from "./model-setup"; -import { assertWindowsNodeMxcModelOnlyChange } from "./windows-node-mxc-model-config"; +import { assertWindowsNodeMxcModelOrPluginChange } from "./windows-node-mxc-model-config"; const ALLOWED_TOP_LEVEL_KEYS = new Set([ "$schema", @@ -80,6 +80,15 @@ export function assertWindowsNodeMxcSearchOnlyChange(before: unknown, after: unk } } +export function isPluginOnlyChange(before: unknown, after: unknown): boolean { + const original = structuredClone(object(before, "Original Gateway configuration")); + const next = structuredClone(object(after, "Gateway configuration")); + const pluginsChanged = !isDeepStrictEqual(original.plugins, next.plugins); + delete original.plugins; + delete next.plugins; + return pluginsChanged && isDeepStrictEqual(original, next); +} + export function assertInitialModelSetupChange( before: unknown, after: unknown, @@ -123,5 +132,5 @@ export function assertInitialModelSetupChange( } comparison.gateway = gateway; } - assertWindowsNodeMxcModelOnlyChange(comparison, next); + assertWindowsNodeMxcModelOrPluginChange(comparison, next); } diff --git a/desktop/src/config-write-service.test.ts b/desktop/src/config-write-service.test.ts index d12f3bd..7424211 100644 --- a/desktop/src/config-write-service.test.ts +++ b/desktop/src/config-write-service.test.ts @@ -51,6 +51,9 @@ function fixture( exists = true; }), applyModel: vi.fn().mockResolvedValue(undefined), + applyPlugins: vi.fn(async (next: unknown) => { + current = structuredClone(next as Record); + }), applySearch: vi.fn(async (next: unknown) => { current = structuredClone(next as Record); }), @@ -99,6 +102,45 @@ function searchChange(before: Record) { } describe("guarded configuration writes", () => { + it.each([ + { entries: { "github-copilot": { enabled: true, config: { option: "value" } } } }, + { allow: ["other"], deny: ["github-copilot"], entries: { other: { enabled: false } } }, + undefined, + ])("applies plugin settings with MXC on: %j", async (plugins) => { + const before = { ...routedConfig(), plugins: { entries: { old: { enabled: true } } } }; + const next: Record = structuredClone(before); + if (plugins === undefined) delete next.plugins; + else next.plugins = plugins; + const state = fixture({ current: before }); + await writeGuardedConfig(state.deps, next, before); + expect(state.deps.requireActiveContainment).toHaveBeenCalledOnce(); + expect(state.deps.applyPlugins).toHaveBeenCalledExactlyOnceWith(next, before); + expect(state.saved()).toEqual(next); + expect(state.deps.persist).not.toHaveBeenCalled(); + }); + + it("does not allow a plugin write to alter command routing or use a stale snapshot", async () => { + const before = routedConfig(); + const next = { ...before, plugins: { entries: { example: { enabled: true } } } }; + const state = fixture({ current: before }); + const unsafe = { ...next, tools: { exec: { host: "gateway" } } }; + await expect(writeGuardedConfig(state.deps, unsafe, before)).rejects.toThrow("Search settings"); + state.setCurrent({ ...before, hooks: { enabled: false } }); + await expect(writeGuardedConfig(state.deps, next, before)).rejects.toThrow("changed"); + expect(state.deps.applyPlugins).not.toHaveBeenCalled(); + }); + + it("does not apply plugin changes if configuration changes while checking MXC readiness", async () => { + const before = routedConfig(); + const next = { ...before, plugins: { entries: { example: { enabled: true } } } }; + const state = fixture({ current: before }); + state.deps.requireActiveContainment.mockImplementation(async () => { + state.setCurrent({ ...before, hooks: { enabled: false } }); + }); + await expect(writeGuardedConfig(state.deps, next, before)).rejects.toThrow("changed"); + expect(state.deps.applyPlugins).not.toHaveBeenCalled(); + }); + it("saves only search settings under attested MXC without changing routing", async () => { const before = routedConfig(); const state = fixture({ current: before }); diff --git a/desktop/src/config-write-service.ts b/desktop/src/config-write-service.ts index 66fcd5b..3794c4c 100644 --- a/desktop/src/config-write-service.ts +++ b/desktop/src/config-write-service.ts @@ -2,6 +2,7 @@ import { assertConfigWriteAllowed, assertInitialModelSetupChange, assertWindowsNodeMxcSearchOnlyChange, + isPluginOnlyChange, } from "./config-write-policy"; import { parseModelConfigUpdate, type ModelConfigUpdate } from "./model-config-application"; import { assertModelConfigUnchanged } from "./model-setup"; @@ -9,7 +10,7 @@ import { applyWindowsNodeCommandPolicy, validateWindowsNodeMxcGatewayPolicy, } from "./windows-node-mxc"; -import { assertWindowsNodeMxcModelOnlyChange } from "./windows-node-mxc-model-config"; +import { assertWindowsNodeMxcModelOrPluginChange } from "./windows-node-mxc-model-config"; interface ConfigWriteDependencies { readConfig(): unknown; @@ -24,6 +25,7 @@ interface ConfigWriteDependencies { nodeId(): string; persist(config: Record): void; applyModel(params: ModelConfigUpdate): Promise; + applyPlugins(config: unknown, expectedConfig: unknown): Promise; applySearch(config: unknown, expectedConfig: unknown, assertCurrent: () => void): Promise; startServices(): Promise; } @@ -114,7 +116,7 @@ export async function writeGuardedConfig( }); assertInitialModelSetupChange(current, config, params.providerKey); if (deps.isGatewayConnected()) { - assertWindowsNodeMxcModelOnlyChange(current ?? {}, config); + assertWindowsNodeMxcModelOrPluginChange(current ?? {}, config); await deps.applyModel(params); return; } @@ -138,6 +140,17 @@ export async function writeGuardedConfig( return; } + if (mxcEnabled && !search && isPluginOnlyChange(current, config)) { + await deps.requireActiveContainment(); + assertCurrent(); + const policy = validateWindowsNodeMxcGatewayPolicy(config, deps.nodeId(), "active"); + if (!policy.ready) { + throw new Error(`Gateway command routing is not ready: ${policy.blockers.join("; ")}`); + } + await deps.applyPlugins(config, expectedConfig); + return; + } + if (mxcEnabled || search) { assertWindowsNodeMxcSearchOnlyChange(current, config); if (mxcEnabled) await deps.requireActiveContainment(); diff --git a/desktop/src/gateway-config-migrations.ts b/desktop/src/gateway-config-migrations.ts new file mode 100644 index 0000000..e9269b4 --- /dev/null +++ b/desktop/src/gateway-config-migrations.ts @@ -0,0 +1,21 @@ +type JsonObject = Record; + +function objectOrEmpty(value: unknown): JsonObject { + return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonObject) : {}; +} + +export function removeGatewayAddedMigrationMarkers( + meta: JsonObject, + expectedMeta: JsonObject, +): void { + const value = meta.migrations; + if (!value || typeof value !== "object" || Array.isArray(value)) return; + const migrations = value as JsonObject; + const expectedMigrations = objectOrEmpty(expectedMeta.migrations); + for (const marker of ["modelPolicyAllowlist", "utilityModelSeparation"]) { + if (!Object.hasOwn(expectedMigrations, marker) && migrations[marker] === true) + delete migrations[marker]; + } + if (!Object.hasOwn(expectedMeta, "migrations") && Object.keys(migrations).length === 0) + delete meta.migrations; +} diff --git a/desktop/src/main.ts b/desktop/src/main.ts index 388d4d0..c082011 100644 --- a/desktop/src/main.ts +++ b/desktop/src/main.ts @@ -40,7 +40,11 @@ import { } from "./internal-features"; import { registerLocalModelHandlers } from "./local-model-ipc"; import { SessionModelService, sessionModelChatKey } from "./session-model-service"; -import { applyModelConfig, parseModelConfigUpdate } from "./model-config-application"; +import { + applyGatewayConfiguration, + applyModelConfig, + parseModelConfigUpdate, +} from "./model-config-application"; import { resolveGatewayRestartReason } from "./gateway-restart-reason"; import { registerSessionModelHandlers } from "./session-model-ipc"; import type { LocalModelReceipt } from "./local-model-types"; @@ -297,8 +301,8 @@ import { applyLiveSandboxMode } from "./windows-node-mxc-live-mode"; import { checkWindowsNodeMxcHealth } from "./windows-node-mxc-health-check"; import { WindowsNodeMxcStatusCache, type MxcStatusSnapshot } from "./windows-node-mxc-status-cache"; import { - assertWindowsNodeMxcModelOnlyChange, - assertWindowsNodeMxcModelSettingsUnchanged, + assertWindowsNodeMxcModelOrPluginChange, + assertWindowsNodeMxcModelAndPluginSettingsUnchanged, runWindowsNodeMxcModelUpdate, } from "./windows-node-mxc-model-config"; import { @@ -673,7 +677,7 @@ function applyModelConfiguration(input: unknown): Promise { const params = parseModelConfigUpdate(input); if (isWindowsNodeMxcDesired()) { assertModelConfigUnchanged(params.expectedConfig, readConfig()); - assertWindowsNodeMxcModelOnlyChange(params.expectedConfig, params.config); + assertWindowsNodeMxcModelOrPluginChange(params.expectedConfig, params.config); } return withWindowsNodeMxcModelUpdate( () => @@ -721,16 +725,19 @@ function prepareProviderCatalogModel(modelRef: string, expectedConfig: unknown): async function withWindowsNodeMxcModelUpdate( operation: () => Promise, resultAfterRestart: () => T, + label: "model" | "plugin" = "model", ): Promise { if (!isWindowsNodeMxcDesired() || windowsNodeMxcModelUpdateInProgress) return operation(); localModelService.assertIdle(); sessionModelService.assertIdle(); if (githubCopilotLoginInProgress || activeModelSessions.size > 0) - throw new Error("Finish the current sign-in or chat response before changing the model"); + throw new Error( + `Finish the current sign-in or chat response before changing ${label} settings`, + ); const requestedMode = getWindowsNodeMxcRequestedMode(); await requireEffectiveWindowsNodeMxc(true); if (getWindowsNodeMxcRequestedMode() !== requestedMode) - throw new Error("Containment mode changed before model setup"); + throw new Error(`Containment mode changed before ${label} setup`); let client = gwClient; let generation = gatewayGenerationId; let child = gatewayProcess; @@ -746,23 +753,26 @@ async function withWindowsNodeMxcModelUpdate( windowsNodeMxcApprovalProofContext !== proofContext || !isManagedGatewayProcessAlive() ) - throw new Error("The managed MXC runtime changed during model setup"); + throw new Error(`The managed MXC runtime changed during ${label} setup`); }; return windowsNodeMxcLifecycleOperations.run( { kind: "update-model" }, async () => { if (activeModelSessions.size > 0 || githubCopilotLoginInProgress) - throw new Error("Finish the current sign-in or chat response before changing the model"); + throw new Error( + `Finish the current sign-in or chat response before changing ${label} settings`, + ); windowsNodeMxcModelUpdateInProgress = true; try { return await runWindowsNodeMxcModelUpdate({ + label: label === "model" ? "Model" : "Plugin", readConfig, pause: async () => { assertCurrent(); windowsNodeMxcActivationInProgress = true; setWindowsNodeMxcLifecycleState( "updating-model", - "Applying model settings with containment locked", + `Applying ${label} settings with containment locked`, ); closeWindowsNodeMxcIngress(); bundledWindowsNodeHost.revokeActivationLease(); @@ -783,12 +793,14 @@ async function withWindowsNodeMxcModelUpdate( ); assertCurrent(); if (snapshot.valid !== true || snapshot.hash !== hash) - throw new Error("The saved model configuration changed before the required restart"); + throw new Error( + `The saved ${label} configuration changed before the required restart`, + ); const saved = structuredClone(readConfig()); await stopGatewayForSecurityTransition(gatewayPort); windowsNodeMxcActivationInProgress = false; await runAutomaticWindowsNodeMxcReadiness(undefined, false); - assertWindowsNodeMxcModelSettingsUnchanged(saved, readConfig()); + assertWindowsNodeMxcModelAndPluginSettingsUnchanged(saved, readConfig()); client = gwClient; generation = gatewayGenerationId; child = gatewayProcess; @@ -809,12 +821,12 @@ async function withWindowsNodeMxcModelUpdate( !snapshot.configRevisionHash || snapshot.appliedConfigHash !== snapshot.configRevisionHash ) - throw new Error("The Gateway has not applied the saved model configuration"); + throw new Error(`The Gateway has not applied the saved ${label} configuration`); await bundledWindowsNodeHost.setActivationLease("active", 120_000); const status = await getWindowsNodeMxcStatus(); assertCurrent(); assertWindowsNodeMxcBaseReady(status, "active", true); - if (!status.effectiveEnabled) throw new Error("MXC model update attestation failed"); + if (!status.effectiveEnabled) throw new Error(`MXC ${label} update attestation failed`); }, resume: () => { assertCurrent(); @@ -824,7 +836,7 @@ async function withWindowsNodeMxcModelUpdate( }, failClosed: () => failClosedWindowsNodeMxc( - "Model configuration could not be confirmed; reload settings and retry containment readiness", + `${label === "model" ? "Model" : "Plugin"} configuration could not be confirmed; reload settings and retry containment readiness`, ), }); } finally { @@ -7600,6 +7612,31 @@ function registerIpcHandlers(): void { writeConfigTextAtomically(JSON.stringify(next, null, 2)); }, applyModel: applyModelConfiguration, + applyPlugins: (next, expected) => + withWindowsNodeMxcModelUpdate( + () => + applyGatewayConfiguration( + { + gateway: () => gwClient, + readConfig, + assertMutable: assertCloudModelMutable, + log: (message) => { + console.info(message); + sendToWindow(mainWindow, "gateway:log", message); + electronLifecycleDiagnostics.log("plugin-config-application", { message }); + }, + }, + { + config: next, + expectedConfig: expected, + context: "[plugin-config]", + note: "Plugin settings", + label: "plugin", + }, + ), + () => undefined, + "plugin", + ), applySearch: (next, expected, assertCurrent) => applySearchConfig( { diff --git a/desktop/src/model-config-application.test.ts b/desktop/src/model-config-application.test.ts index 02e8670..6bf500c 100644 --- a/desktop/src/model-config-application.test.ts +++ b/desktop/src/model-config-application.test.ts @@ -1,5 +1,11 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { applyModelConfig, type ModelConfigUpdate } from "./model-config-application"; +import { + applyGatewayConfiguration, + applyModelConfig, + type ModelConfigUpdate, +} from "./model-config-application"; +import { ensureGitHubCopilotProviderPlugin } from "./model-provider-plugins"; +import { runWindowsNodeMxcModelUpdate } from "./windows-node-mxc-model-config"; function fixture() { const before = { @@ -64,6 +70,103 @@ function fixture() { afterEach(() => vi.useRealTimers()); describe("applyModelConfig", () => { + it("applies Copilot activation through the MXC model transaction", async () => { + const state = fixture(); + const next = structuredClone(state.input.expectedConfig) as Record; + ensureGitHubCopilotProviderPlugin(next); + state.input = { + ...state.input, + config: next, + action: "copilot-prepare", + providerKey: "github-copilot", + }; + const hooks = { + readConfig: state.deps.readConfig, + pause: vi.fn(async () => {}), + apply: () => applyModelConfig(state.deps, state.input), + restartSavedConfig: vi.fn(async () => {}), + verify: vi.fn(async () => {}), + resume: vi.fn(), + failClosed: vi.fn(async () => {}), + }; + await runWindowsNodeMxcModelUpdate(hooks); + expect(state.saved()).toEqual(next); + expect(hooks.resume).toHaveBeenCalledOnce(); + expect(hooks.failClosed).not.toHaveBeenCalled(); + }); + + it("applies plugin settings through the same revision-guarded Gateway path", async () => { + const state = fixture(); + const next = { + ...(state.input.expectedConfig as object), + plugins: { entries: { "github-copilot": { enabled: true } } }, + }; + await applyGatewayConfiguration(state.deps, { + config: next, + expectedConfig: state.input.expectedConfig, + context: "[plugin-config]", + note: "Plugin settings", + label: "plugin", + }); + expect(state.gateway.request).toHaveBeenCalledWith( + "config.apply", + { baseHash: "before", raw: JSON.stringify(next), note: "Plugin settings" }, + 30_000, + ); + expect(state.saved()).toEqual(next); + }); + + it("does not report success when the Gateway did not save the requested plugin settings", async () => { + const state = fixture(); + const next = { + ...(state.input.expectedConfig as object), + plugins: { entries: { "github-copilot": { enabled: true } } }, + }; + state.gateway.request.mockImplementation(async (method) => { + if (method === "config.apply") return { ok: true, hash: "before" }; + return state.snapshot(); + }); + await expect( + applyGatewayConfiguration(state.deps, { + config: next, + expectedConfig: state.input.expectedConfig, + context: "[plugin-config]", + note: "Plugin settings", + label: "plugin", + }), + ).rejects.toMatchObject({ + cause: { message: "The saved plugin settings do not match the requested settings" }, + }); + }); + + it("does not restart for plugin changes that were not saved as requested", async () => { + const state = fixture(); + const next = { + ...(state.input.expectedConfig as object), + plugins: { entries: { "github-copilot": { enabled: true } } }, + }; + state.gateway.request.mockImplementation(async (method) => { + if (method === "config.apply") + return { + ok: true, + hash: "after", + sentinel: { payload: { stats: { requiresRestart: true } } }, + }; + return state.snapshot(); + }); + await expect( + applyGatewayConfiguration(state.deps, { + config: next, + expectedConfig: state.input.expectedConfig, + context: "[plugin-config]", + note: "Plugin settings", + label: "plugin", + }), + ).rejects.toMatchObject({ + cause: { message: "The saved plugin settings do not match the requested settings" }, + }); + }); + it("applies the complete configuration with a revision guard and confirms runtime application", async () => { const state = fixture(); await applyModelConfig(state.deps, state.input); diff --git a/desktop/src/model-config-application.ts b/desktop/src/model-config-application.ts index 229b24d..1772b10 100644 --- a/desktop/src/model-config-application.ts +++ b/desktop/src/model-config-application.ts @@ -63,14 +63,35 @@ export function parseModelConfigUpdate(input: unknown): ModelConfigUpdate { export async function applyModelConfig(deps: Dependencies, input: unknown): Promise { const params = parseModelConfigUpdate(input); + return applyGatewayConfiguration(deps, { + config: params.config, + expectedConfig: params.expectedConfig, + context: `[model-config] action=${params.action} provider=${params.providerKey}`, + note: `${params.action}: ${params.providerKey}`, + label: "model", + }); +} + +export async function applyGatewayConfiguration( + deps: Dependencies, + params: { + config: unknown; + expectedConfig: unknown; + context: string; + note: string; + label: "model" | "plugin"; + }, +): Promise { deps.assertMutable(); assertConfigWriteAllowed(params.config, params.expectedConfig); assertModelConfigUnchanged(params.expectedConfig, deps.readConfig()); const gateway = deps.gateway(); if (!gateway?.connected || !supportsLocalModelGatewayVersion(gateway.serverVersion)) - throw new Error("Applying model settings requires a connected, supported OpenClaw Gateway"); + throw new Error( + `Applying ${params.label} settings requires a connected, supported OpenClaw Gateway`, + ); if (!["config.get", "config.apply"].every((method) => gateway.methods.includes(method))) - throw new Error("Gateway cannot hot-apply model settings"); + throw new Error(`Gateway cannot hot-apply ${params.label} settings`); const generation = gateway.connectionGeneration; const assertCurrent = () => { deps.assertMutable(); @@ -79,15 +100,24 @@ export async function applyModelConfig(deps: Dependencies, input: unknown): Prom !gateway.connected || gateway.connectionGeneration !== generation ) - throw new Error("Gateway connection changed; reload model settings before retrying"); + throw new Error( + `Gateway connection changed; reload ${params.label} settings before retrying`, + ); }; - const context = `[model-config] action=${params.action} provider=${params.providerKey}`; + const context = params.context; const snapshot = object(await gateway.request("config.get", {})); assertCurrent(); assertModelConfigUnchanged(params.expectedConfig, deps.readConfig()); if (snapshot.valid !== true || typeof snapshot.hash !== "string" || !snapshot.hash) throw new Error("The Gateway configuration is unavailable or invalid"); let targetHash = snapshot.hash; + const assertRequestedPluginsSaved = () => { + if ( + !isDeepStrictEqual(object(params.config).plugins, object(params.expectedConfig).plugins) && + !isDeepStrictEqual(object(deps.readConfig()).plugins, object(params.config).plugins) + ) + throw new Error("The saved plugin settings do not match the requested settings"); + }; deps.log(`${context} status=applying`); try { if (!isDeepStrictEqual(params.config, params.expectedConfig)) { @@ -97,16 +127,18 @@ export async function applyModelConfig(deps: Dependencies, input: unknown): Prom { baseHash: snapshot.hash, raw: JSON.stringify(params.config), - note: `${params.action}: ${params.providerKey}`, + note: params.note, }, MODEL_APPLY_SETTLE_TIMEOUT_MS, ), ); assertCurrent(); if (result.ok !== true || typeof result.hash !== "string" || !result.hash) - throw new Error("The saved model configuration could not be confirmed"); - if (object(object(object(result.sentinel).payload).stats).requiresRestart === true) + throw new Error(`The saved ${params.label} configuration could not be confirmed`); + if (object(object(object(result.sentinel).payload).stats).requiresRestart === true) { + assertRequestedPluginsSaved(); throw new ModelConfigRestartRequiredError(result.hash); + } targetHash = result.hash; } const deadline = Date.now() + MODEL_APPLY_SETTLE_TIMEOUT_MS; @@ -116,16 +148,20 @@ export async function applyModelConfig(deps: Dependencies, input: unknown): Prom ); assertCurrent(); if (applied.valid !== true || applied.hash !== targetHash) - throw new Error("The model configuration changed while applying; reload settings"); + throw new Error( + `The ${params.label} configuration changed while applying; reload settings`, + ); if ( typeof applied.configRevisionHash === "string" && applied.configRevisionHash && applied.appliedConfigHash === applied.configRevisionHash ) { + assertRequestedPluginsSaved(); deps.log(`${context} status=hot-applied`); return; } - if (Date.now() >= deadline) throw new Error("The model configuration is still being applied"); + if (Date.now() >= deadline) + throw new Error(`The ${params.label} configuration is still being applied`); await new Promise((resolve) => setTimeout(resolve, 500)); } } catch (cause) { @@ -136,7 +172,7 @@ export async function applyModelConfig(deps: Dependencies, input: unknown): Prom ) throw cause; throw new Error( - "Model configuration application could not be confirmed. It may have been saved; reload settings before retrying. No restart or retry was attempted by MicroClaw.", + `${params.label === "model" ? "Model" : "Plugin"} configuration application could not be confirmed. It may have been saved; reload settings before retrying. No restart or retry was attempted by MicroClaw.`, { cause }, ); } diff --git a/desktop/src/search-config-application.ts b/desktop/src/search-config-application.ts index a3ab030..3b46826 100644 --- a/desktop/src/search-config-application.ts +++ b/desktop/src/search-config-application.ts @@ -1,5 +1,6 @@ import { isDeepStrictEqual } from "node:util"; import { MODEL_APPLY_SETTLE_TIMEOUT_MS } from "./constants"; +import { removeGatewayAddedMigrationMarkers } from "./gateway-config-migrations"; import { assertModelConfigUnchanged } from "./model-setup"; import { assertSearchProviderPluginActive, @@ -54,17 +55,8 @@ function withoutTargetPluginChanges( const meta = object(config.meta); delete meta.lastTouchedVersion; if (Object.hasOwn(meta, "migrations")) { - const migrations = object(meta.migrations); - const expectedMigrations = optionalObject(optionalObject(expected.meta).migrations); - for (const marker of ["modelPolicyAllowlist", "utilityModelSeparation"]) { - if (!Object.hasOwn(expectedMigrations, marker) && migrations[marker] === true) - delete migrations[marker]; - } - if ( - !Object.hasOwn(optionalObject(expected.meta), "migrations") && - !Object.keys(migrations).length - ) - delete meta.migrations; + object(meta.migrations); + removeGatewayAddedMigrationMarkers(meta, optionalObject(expected.meta)); } if (!Object.hasOwn(expected, "meta") && Object.keys(meta).length === 0) delete config.meta; } diff --git a/desktop/src/windows-node-mxc-model-config.test.ts b/desktop/src/windows-node-mxc-model-config.test.ts index 9f27a11..3a5146e 100644 --- a/desktop/src/windows-node-mxc-model-config.test.ts +++ b/desktop/src/windows-node-mxc-model-config.test.ts @@ -1,8 +1,9 @@ import { describe, expect, it, vi } from "vitest"; import { ModelConfigRestartRequiredError } from "./model-setup"; +import { ensureGitHubCopilotProviderPlugin } from "./model-provider-plugins"; import { - assertWindowsNodeMxcModelOnlyChange, - assertWindowsNodeMxcModelSettingsUnchanged, + assertWindowsNodeMxcModelOrPluginChange, + assertWindowsNodeMxcModelAndPluginSettingsUnchanged, runWindowsNodeMxcModelUpdate, } from "./windows-node-mxc-model-config"; @@ -17,21 +18,27 @@ function config() { }; } -describe("MXC model-only configuration boundary", () => { +describe("MXC model and plugin configuration boundary", () => { it("binds restarted model settings while allowing Gateway-owned metadata to change", () => { const before = config(); expect(() => - assertWindowsNodeMxcModelSettingsUnchanged(before, { + assertWindowsNodeMxcModelAndPluginSettingsUnchanged(before, { ...before, meta: { lastTouchedAt: "new" }, }), ).not.toThrow(); expect(() => - assertWindowsNodeMxcModelSettingsUnchanged(before, { + assertWindowsNodeMxcModelAndPluginSettingsUnchanged(before, { ...before, models: { providers: { unexpected: {} } }, }), - ).toThrow("saved model settings changed"); + ).toThrow("saved model or plugin settings changed"); + expect(() => + assertWindowsNodeMxcModelAndPluginSettingsUnchanged(before, { + ...before, + plugins: { entries: { "github-copilot": { enabled: false } } }, + }), + ).toThrow("saved model or plugin settings changed"); }); it("allows provider credentials, model definitions and selectors without mutating its inputs", () => { const before = config(); @@ -57,7 +64,7 @@ describe("MXC model-only configuration boundary", () => { }, }; const original = structuredClone(after); - expect(() => assertWindowsNodeMxcModelOnlyChange(before, after)).not.toThrow(); + expect(() => assertWindowsNodeMxcModelOrPluginChange(before, after)).not.toThrow(); expect(after).toEqual(original); }); @@ -69,31 +76,92 @@ describe("MXC model-only configuration boundary", () => { agents: { defaults: { model: "qwen/qwen-plus" } }, meta: { lastTouchedAt: "now", lastTouchedVersion: "version" }, }; - expect(() => assertWindowsNodeMxcModelOnlyChange(before, after)).not.toThrow(); - expect(() => assertWindowsNodeMxcModelOnlyChange(after, before)).not.toThrow(); + expect(() => assertWindowsNodeMxcModelOrPluginChange(before, after)).not.toThrow(); + expect(() => assertWindowsNodeMxcModelOrPluginChange(after, before)).not.toThrow(); }); - it.each([ - "tools", - "gateway", - "plugins", - "hooks", - "cron", - "sandbox", - "permissions", - "channels", - "unknown", - ])("rejects a %s change even when it accompanies a model update", (key) => { + it("allows only new, enabled Gateway migration markers during an update", () => { const before = config(); + const after = { + ...before, + plugins: { entries: { "github-copilot": { enabled: true } } }, + meta: { + lastTouchedVersion: "2026.10.10", + migrations: { modelPolicyAllowlist: true, utilityModelSeparation: true }, + }, + }; + expect(() => assertWindowsNodeMxcModelOrPluginChange(before, after)).not.toThrow(); + expect(after.meta.migrations).toEqual({ + modelPolicyAllowlist: true, + utilityModelSeparation: true, + }); expect(() => - assertWindowsNodeMxcModelOnlyChange(before, { - ...before, - models: { providers: { qwen: {} } }, - [key]: { changed: true }, + assertWindowsNodeMxcModelOrPluginChange(before, { + ...after, + meta: { migrations: { modelPolicyAllowlist: false } }, + }), + ).toThrow("Other Gateway configuration remains locked"); + expect(() => + assertWindowsNodeMxcModelOrPluginChange(before, { + ...after, + meta: { migrations: { unexpected: true } }, }), ).toThrow("Other Gateway configuration remains locked"); + const existing = { ...before, meta: { migrations: { modelPolicyAllowlist: false } } }; + expect(() => assertWindowsNodeMxcModelOrPluginChange(existing, after)).toThrow( + "Other Gateway configuration remains locked", + ); + }); + + it("allows unrestricted plugin configuration changes alongside model updates", () => { + const before = { + ...config(), + plugins: { allow: ["old"], entries: { old: { enabled: true } } }, + }; + const after = { + ...config(), + models: { providers: { copilot: {} } }, + plugins: { + allow: ["github-copilot"], + deny: ["old"], + entries: { "github-copilot": { enabled: true, config: { option: "value" } } }, + }, + }; + expect(() => assertWindowsNodeMxcModelOrPluginChange(before, after)).not.toThrow(); + expect(() => assertWindowsNodeMxcModelOrPluginChange(after, before)).not.toThrow(); + }); + + it("allows the Copilot provider helper to enable a denied plugin during model setup", () => { + const before = { + ...config(), + plugins: { + allow: ["other"], + deny: ["github-copilot"], + entries: { "github-copilot": { enabled: false } }, + }, + }; + const after = structuredClone(before); + expect(ensureGitHubCopilotProviderPlugin(after)).toBe(true); + expect(() => assertWindowsNodeMxcModelOrPluginChange(before, after)).not.toThrow(); + expect(after.plugins.entries["github-copilot"].enabled).toBe(true); + expect(after.plugins.allow).toContain("github-copilot"); + expect(after.plugins.deny).not.toContain("github-copilot"); }); + it.each(["tools", "gateway", "hooks", "cron", "sandbox", "permissions", "channels", "unknown"])( + "rejects a %s change even when it accompanies a model update", + (key) => { + const before = config(); + expect(() => + assertWindowsNodeMxcModelOrPluginChange(before, { + ...before, + models: { providers: { qwen: {} } }, + [key]: { changed: true }, + }), + ).toThrow("Other Gateway configuration remains locked"); + }, + ); + it.each([ { defaults: { tools: { allow: ["*"] } } }, { defaults: { workspace: "C:\\Other" } }, @@ -102,7 +170,7 @@ describe("MXC model-only configuration boundary", () => { ])("rejects agent policy and roster changes: %j", (agents) => { const before = config(); expect(() => - assertWindowsNodeMxcModelOnlyChange(before, { + assertWindowsNodeMxcModelOrPluginChange(before, { ...before, agents: { ...before.agents, ...agents }, }), @@ -117,7 +185,7 @@ describe("MXC model-only configuration boundary", () => { { models: [] }, { models: { providers: null } }, ])("rejects malformed configuration: %j", (after) => { - expect(() => assertWindowsNodeMxcModelOnlyChange(config(), after)).toThrow(); + expect(() => assertWindowsNodeMxcModelOrPluginChange(config(), after)).toThrow(); }); }); @@ -165,6 +233,35 @@ describe("MXC model update transaction", () => { expect(state.hooks.restartSavedConfig).not.toHaveBeenCalled(); }); + it("accepts plugin activation during the guarded model update", async () => { + const state = transaction(); + state.hooks.apply.mockImplementation(async () => { + state.setConfig({ + ...config(), + plugins: { entries: { "github-copilot": { enabled: true } } }, + }); + return "selected"; + }); + await expect(runWindowsNodeMxcModelUpdate(state.hooks)).resolves.toBe("selected"); + expect(state.calls).toEqual(["pause", "verify", "resume"]); + }); + + it("accepts Gateway migration markers written when the plugin is activated", async () => { + const state = transaction(); + state.hooks.apply.mockImplementation(async () => { + state.setConfig({ + ...config(), + plugins: { entries: { "github-copilot": { enabled: true } } }, + meta: { + migrations: { modelPolicyAllowlist: true, utilityModelSeparation: true }, + }, + }); + return "selected"; + }); + await expect(runWindowsNodeMxcModelUpdate(state.hooks)).resolves.toBe("selected"); + expect(state.hooks.resume).toHaveBeenCalledOnce(); + }); + it("restarts only an explicitly acknowledged saved revision, never repeating the write", async () => { const state = transaction(); state.hooks.apply.mockRejectedValue( diff --git a/desktop/src/windows-node-mxc-model-config.ts b/desktop/src/windows-node-mxc-model-config.ts index 15c239c..4cafdfd 100644 --- a/desktop/src/windows-node-mxc-model-config.ts +++ b/desktop/src/windows-node-mxc-model-config.ts @@ -1,4 +1,5 @@ import { isDeepStrictEqual } from "node:util"; +import { removeGatewayAddedMigrationMarkers } from "./gateway-config-migrations"; import { assertModelConfigUnchanged, ModelConfigRestartRequiredError } from "./model-setup"; type JsonObject = Record; @@ -9,13 +10,14 @@ function object(value: unknown): JsonObject { return value as JsonObject; } -function nonModelConfiguration(value: unknown): JsonObject { +function nonModelOrPluginConfiguration(value: unknown, expectedMeta: JsonObject): JsonObject { const config = structuredClone(object(value)); if (config.models !== undefined) { const models = object(config.models); if (models.providers !== undefined) object(models.providers); } delete config.models; + delete config.plugins; if (config.agents !== undefined) { const agents = object(config.agents); if (agents.defaults !== undefined) { @@ -28,29 +30,47 @@ function nonModelConfiguration(value: unknown): JsonObject { } if (config.meta !== undefined) { const meta = object(config.meta); - // The Gateway stamps these fields when committing an otherwise model-only update. + // The Gateway stamps these fields when committing a configuration update. delete meta.lastTouchedAt; delete meta.lastTouchedVersion; + removeGatewayAddedMigrationMarkers(meta, expectedMeta); if (Object.keys(meta).length === 0) delete config.meta; } return config; } -export function assertWindowsNodeMxcModelOnlyChange(before: unknown, after: unknown): void { - if (!isDeepStrictEqual(nonModelConfiguration(before), nonModelConfiguration(after))) +export function assertWindowsNodeMxcModelOrPluginChange(before: unknown, after: unknown): void { + const config = object(before); + const expectedMeta = config.meta === undefined ? {} : object(config.meta); + if ( + !isDeepStrictEqual( + nonModelOrPluginConfiguration(before, expectedMeta), + nonModelOrPluginConfiguration(after, expectedMeta), + ) + ) throw new Error( - "MXC model setup may change only model providers, the default model and per-model settings. Other Gateway configuration remains locked.", + "MXC configuration update may change only model or plugin settings. Other Gateway configuration remains locked.", ); } -export function assertWindowsNodeMxcModelSettingsUnchanged(before: unknown, after: unknown): void { +export function assertWindowsNodeMxcModelAndPluginSettingsUnchanged( + before: unknown, + after: unknown, +): void { const project = (value: unknown) => { const config = object(value); const defaults = object(object(config.agents ?? {}).defaults ?? {}); - return { models: config.models, model: defaults.model, defaultsModels: defaults.models }; + return { + models: config.models, + model: defaults.model, + defaultsModels: defaults.models, + plugins: config.plugins, + }; }; if (!isDeepStrictEqual(project(before), project(after))) - throw new Error("The saved model settings changed during the required Gateway restart"); + throw new Error( + "The saved model or plugin settings changed during the required Gateway restart", + ); } function restartHash(error: unknown): string | null { @@ -64,6 +84,7 @@ function restartHash(error: unknown): string | null { } export interface WindowsNodeMxcModelUpdateHooks { + label?: "Model" | "Plugin"; readConfig(): unknown; pause(): Promise; apply(): Promise; @@ -76,6 +97,7 @@ export interface WindowsNodeMxcModelUpdateHooks { export async function runWindowsNodeMxcModelUpdate( hooks: WindowsNodeMxcModelUpdateHooks, ): Promise { + const label = hooks.label ?? "Model"; const before = structuredClone(hooks.readConfig()); try { await hooks.pause(); @@ -85,11 +107,11 @@ export async function runWindowsNodeMxcModelUpdate( } catch (error) { const hash = restartHash(error); if (!hash) throw error; - assertWindowsNodeMxcModelOnlyChange(before, hooks.readConfig()); + assertWindowsNodeMxcModelOrPluginChange(before, hooks.readConfig()); result = await hooks.restartSavedConfig(hash); } const applied = structuredClone(hooks.readConfig()); - assertWindowsNodeMxcModelOnlyChange(before, applied); + assertWindowsNodeMxcModelOrPluginChange(before, applied); await hooks.verify(); assertModelConfigUnchanged(applied, hooks.readConfig()); hooks.resume(); @@ -100,12 +122,12 @@ export async function runWindowsNodeMxcModelUpdate( } catch (lockingError) { throw new AggregateError( [error, lockingError], - "Model update could not be confirmed and MXC recovery failed. Execution remains locked.", + `${label} update could not be confirmed and MXC recovery failed. Execution remains locked.`, { cause: lockingError }, ); } throw new Error( - "Model update could not be confirmed. It may have been saved; execution remains locked. Reload settings and retry MXC readiness before continuing.", + `${label} update could not be confirmed. It may have been saved; execution remains locked. Reload settings and retry MXC readiness before continuing.`, { cause: error }, ); } diff --git a/docs/experimental-windows-node-mxc.md b/docs/experimental-windows-node-mxc.md index 5da7dc6..6a91223 100644 --- a/docs/experimental-windows-node-mxc.md +++ b/docs/experimental-windows-node-mxc.md @@ -141,6 +141,10 @@ configured. An existing allowlist is preserved; if it excludes the bundled is explicitly enabled. Browser control is a Gateway capability outside MXC, not the Windows Node command-execution sandbox. +Plugin settings can be changed while MXC is on, including enabling a model +provider plugin. Gateway configuration writes retain revision checks and +containment readiness checks; a plugin change may require a Gateway restart. + Web-search settings remain available in either mode. When a selected provider needs its OpenClaw plugin, MicroClaw installs or enables the plugin matching the running Gateway version, applies the search configuration, and verifies its From b56df8360d8abaee8aa7fd4ccdb9c19ff7ec98e0 Mon Sep 17 00:00:00 2001 From: Tao Sun Date: Wed, 18 Nov 2026 15:48:50 +0800 Subject: [PATCH 2/2] Scope MXC recovery guidance to active sandbox mode Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- CLAUDE.md | 2 +- desktop/src/agent-personas.test.ts | 189 +++++++++++- desktop/src/agent-personas.ts | 96 +++++- desktop/src/agent-workspaces-startup.test.ts | 74 ++++- desktop/src/main.ts | 64 +++- .../windows-node-command-instructions.test.ts | 288 ++++++++++++++++-- .../src/windows-node-command-instructions.ts | 233 +++++++++++++- .../src/windows-node-mxc-live-mode.test.ts | 172 +++++++++++ .../windows-node-mxc-powershell-scope.test.ts | 18 ++ docs/experimental-windows-node-mxc.md | 38 ++- 10 files changed, 1097 insertions(+), 77 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 4bc690e..0b18e71 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Project Overview -MicroClaw is a Windows desktop application that packages the OpenClaw open-source Agent framework. It includes an Electron chat UI, a local OpenClaw Gateway, 52+ built-in skills, 7 managed skills, a native Windows Node + MXC tool sandbox, a WeChat plugin, and a Teams bot integration. MXC Full/Limited are the only sandbox modes; Off deliberately runs tools unsandboxed. The retired AppContainerLauncher backend, preload hooks, provisioning, and controls must not be reintroduced. +MicroClaw is a Windows desktop application that packages the OpenClaw open-source Agent framework. It includes an Electron chat UI, a local OpenClaw Gateway, 52+ built-in skills, 7 managed skills, a native Windows Node + MXC tool sandbox, a WeChat plugin, and a Teams bot integration. MXC Full is the only supported sandbox mode; Off deliberately runs tools unsandboxed. Legacy Limited selections migrate to Full. The retired AppContainerLauncher backend, preload hooks, provisioning, and controls must not be reintroduced. ## Build & Development Commands diff --git a/desktop/src/agent-personas.test.ts b/desktop/src/agent-personas.test.ts index 5108b6b..96b6a07 100644 --- a/desktop/src/agent-personas.test.ts +++ b/desktop/src/agent-personas.test.ts @@ -1,6 +1,8 @@ import * as fs from "fs"; import * as os from "os"; import * as path from "path"; +import { runInNewContext } from "node:vm"; +import ts from "typescript"; import { afterEach, describe, expect, it } from "vitest"; import { getAgentSkills, matchesSkill, resolveSkillFilterNames } from "./agent-catalog"; import { @@ -17,10 +19,15 @@ import { OFFICE_ARTISAN_ARTIFACT_BOUNDARY_SECTION, removeConfiguredAgent, resolveAgentPersonaWorkspace, + seedAgentPersonaWorkspace, seedAgentPersonaWorkspaces, + synchronizeAgentWindowsNodeInstructions, } from "./agent-personas"; import { readAgentRoster } from "./agent-roster"; -import { WINDOWS_NODE_ACCESS_INSTRUCTIONS } from "./windows-node-command-instructions"; +import { + updateWindowsNodeInstructions, + WINDOWS_NODE_ACCESS_INSTRUCTIONS, +} from "./windows-node-command-instructions"; const tempDirs: string[] = []; @@ -350,11 +357,191 @@ My custom transport guidance. expect(updated).toContain(soulPath); expect(soul).toContain("My custom folder guidance."); expect(soul).toContain("My custom transport guidance."); + expect(soul).toContain("## MXC filesystem and executable recovery"); expect(soul).toContain("## PowerShell command quoting"); + expect(soul).toContain("## PowerShell filesystem operations in MXC"); expect(soul).not.toContain("## PowerShell deletion in MXC"); } }); + it("keeps MXC guidance synchronized across main, specialist, and newly added agents", () => { + const stateDir = createStateDir(); + const config = { agents: {} }; + const main = getAgentPersona("main")!; + const specialist = getAgentPersona("code-geek")!; + const legacy = "Legacy generated appendix"; + ensureAgentPersonasConfig(config, stateDir, [...DEFAULT_AGENT_PERSONAS, specialist]); + seedAgentPersonaWorkspaces( + config, + stateDir, + WINDOWS_NODE_ACCESS_INSTRUCTIONS, + {}, + undefined, + undefined, + legacy, + false, + ); + const paths = [main, specialist].map((persona) => + path.join(resolveAgentPersonaWorkspace(config, stateDir, persona), "SOUL.md"), + ); + for (const file of paths) { + expect(fs.readFileSync(file, "utf-8")).not.toMatch(/\bMXC\b|\[declare-access\]/); + fs.appendFileSync(file, "\n## User notes\nPreserve these.\n"); + } + + expect( + synchronizeAgentWindowsNodeInstructions(config, stateDir, legacy, true).updatedFiles, + ).toEqual(expect.arrayContaining(paths)); + for (const file of paths) { + const soul = fs.readFileSync(file, "utf-8"); + expect(soul).toContain("## MXC filesystem and executable recovery"); + expect(soul).toContain("## PowerShell filesystem operations in MXC"); + expect(soul).toContain("## User notes\nPreserve these."); + } + expect( + synchronizeAgentWindowsNodeInstructions(config, stateDir, legacy, false).updatedFiles, + ).toEqual(expect.arrayContaining(paths)); + for (const file of paths) { + const soul = fs.readFileSync(file, "utf-8"); + expect(soul).not.toMatch(/\bMXC\b|\[declare-access\]/); + expect(soul).toContain("## User notes\nPreserve these."); + expect(soul).toContain("## Memory recall before filesystem tools"); + } + expect( + synchronizeAgentWindowsNodeInstructions(config, stateDir, legacy, false).updatedFiles, + ).toEqual([]); + + const added = getAgentPersona("master-archive")!; + ensureAgentPersonasConfig(config, stateDir, [...DEFAULT_AGENT_PERSONAS, specialist, added]); + seedAgentPersonaWorkspace( + config, + stateDir, + added, + WINDOWS_NODE_ACCESS_INSTRUCTIONS, + {}, + undefined, + undefined, + legacy, + false, + ); + const addedSoul = fs.readFileSync( + path.join(resolveAgentPersonaWorkspace(config, stateDir, added), "SOUL.md"), + "utf-8", + ); + expect(addedSoul).not.toMatch(/\bMXC\b|\[declare-access\]/); + expect(addedSoul).toContain("## Windows Node command transport"); + }); + + it("does not partially update agent instructions if a workspace cannot be read", () => { + const stateDir = createStateDir(); + const config = { agents: {} }; + const main = getAgentPersona("main")!; + const specialist = getAgentPersona("code-geek")!; + const legacy = "Legacy generated appendix"; + ensureAgentPersonasConfig(config, stateDir, [...DEFAULT_AGENT_PERSONAS, specialist]); + seedAgentPersonaWorkspaces( + config, + stateDir, + WINDOWS_NODE_ACCESS_INSTRUCTIONS, + {}, + undefined, + undefined, + legacy, + false, + ); + const mainPath = path.join(resolveAgentPersonaWorkspace(config, stateDir, main), "SOUL.md"); + const before = fs.readFileSync(mainPath, "utf-8"); + fs.unlinkSync(path.join(resolveAgentPersonaWorkspace(config, stateDir, specialist), "SOUL.md")); + + expect(() => synchronizeAgentWindowsNodeInstructions(config, stateDir, legacy, true)).toThrow(); + expect(fs.readFileSync(mainPath, "utf-8")).toBe(before); + }); + + it("restores earlier SOUL files if a later workspace write fails", () => { + const stateDir = createStateDir(); + const config = { agents: {} }; + const main = getAgentPersona("main")!; + const specialist = getAgentPersona("code-geek")!; + const legacy = "Legacy generated appendix"; + ensureAgentPersonasConfig(config, stateDir, [...DEFAULT_AGENT_PERSONAS, specialist]); + seedAgentPersonaWorkspaces( + config, + stateDir, + WINDOWS_NODE_ACCESS_INSTRUCTIONS, + {}, + undefined, + undefined, + legacy, + false, + ); + const mainPath = path.join(resolveAgentPersonaWorkspace(config, stateDir, main), "SOUL.md"); + const specialistPath = path.join( + resolveAgentPersonaWorkspace(config, stateDir, specialist), + "SOUL.md", + ); + const before = fs.readFileSync(mainPath, "utf-8"); + const source = fs.readFileSync(path.join(__dirname, "agent-personas.ts"), "utf-8"); + const ast = ts.createSourceFile("agent-personas.ts", source, ts.ScriptTarget.Latest, true); + const declaration = ast.statements.find( + (statement) => + ts.isFunctionDeclaration(statement) && + statement.name?.text === "synchronizeAgentWindowsNodeInstructions", + ); + if (!declaration) throw new Error("Cannot locate agent instruction synchronization"); + const js = ts.transpileModule( + `exports.sync = ${declaration.getText(ast).replace(/^export\s+/, "")}`, + { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }, + ).outputText; + const exported: { sync?: typeof synchronizeAgentWindowsNodeInstructions } = {}; + runInNewContext(js, { + exports: exported, + fs: { + readFileSync: fs.readFileSync, + writeFileSync: (file: string, data: string) => { + if (file === specialistPath) throw new Error("SOUL write failed"); + fs.writeFileSync(file, data, "utf-8"); + }, + }, + os, + path, + process, + AGENT_PERSONAS, + listConfiguredAgents, + resolveAgentPersonaWorkspace, + updateWindowsNodeInstructions, + }); + expect(() => exported.sync!(config, stateDir, legacy, true)).toThrow("SOUL write failed"); + expect(fs.readFileSync(mainPath, "utf-8")).toBe(before); + }); + + it("rolls back a mode update without overwriting subsequent user edits", () => { + const stateDir = createStateDir(); + const config = { agents: {} }; + const main = getAgentPersona("main")!; + const specialist = getAgentPersona("code-geek")!; + const legacy = "Legacy generated appendix"; + ensureAgentPersonasConfig(config, stateDir, [...DEFAULT_AGENT_PERSONAS, specialist]); + seedAgentPersonaWorkspaces( + config, + stateDir, + WINDOWS_NODE_ACCESS_INSTRUCTIONS, + {}, + undefined, + undefined, + legacy, + false, + ); + const mainPath = path.join(resolveAgentPersonaWorkspace(config, stateDir, main), "SOUL.md"); + const before = fs.readFileSync(mainPath, "utf-8"); + + synchronizeAgentWindowsNodeInstructions(config, stateDir, legacy, true).rollback(); + expect(fs.readFileSync(mainPath, "utf-8")).toBe(before); + const update = synchronizeAgentWindowsNodeInstructions(config, stateDir, legacy, true); + fs.appendFileSync(mainPath, "\nUser edited during the update.\n"); + expect(update.rollback).toThrow("Failed to restore agent instructions"); + expect(fs.readFileSync(mainPath, "utf-8")).toContain("User edited during the update."); + }); + it("seeds the Intel Analyst workspace with its research context", () => { const stateDir = createStateDir(); const config = { agents: {} }; diff --git a/desktop/src/agent-personas.ts b/desktop/src/agent-personas.ts index 4ecc26b..5c45251 100644 --- a/desktop/src/agent-personas.ts +++ b/desktop/src/agent-personas.ts @@ -1133,6 +1133,7 @@ export function seedAgentPersonaWorkspaces( homeDir = os.homedir(), cwd = process.cwd(), legacySoulAppendix = "", + mxcEnabled = true, ): string[] { const updatedFiles: string[] = []; const configuredIds = new Set(listConfiguredAgents(config).map((agent) => agent.id)); @@ -1149,6 +1150,7 @@ export function seedAgentPersonaWorkspaces( homeDir, cwd, legacySoulAppendix, + mxcEnabled, ), ); } @@ -1165,10 +1167,14 @@ export function seedAgentPersonaWorkspace( homeDir = os.homedir(), cwd = process.cwd(), legacySoulAppendix = "", + mxcEnabled = true, ): string[] { if (!persona.workspaceFiles) return []; const updatedFiles: string[] = []; const workspaceDir = resolveAgentPersonaWorkspace(config, stateDir, persona, env, homeDir, cwd); + const effectiveSoulAppendix = legacySoulAppendix + ? updateWindowsNodeInstructions(soulAppendix, legacySoulAppendix, mxcEnabled) + : soulAppendix; fs.mkdirSync(workspaceDir, { recursive: true }); for (const [filename, source] of Object.entries(persona.workspaceFiles)) { @@ -1183,7 +1189,7 @@ export function seedAgentPersonaWorkspace( if (fs.existsSync(filePath)) { let existing = fs.readFileSync(filePath, "utf-8"); if (filename === "SOUL.md" && legacySoulAppendix) { - const updated = updateWindowsNodeInstructions(existing, legacySoulAppendix); + const updated = updateWindowsNodeInstructions(existing, legacySoulAppendix, mxcEnabled); if (updated !== existing) { fs.writeFileSync(filePath, updated, "utf-8"); updatedFiles.push(filePath); @@ -1245,14 +1251,14 @@ export function seedAgentPersonaWorkspace( if (requiredMarker && !existing.includes(requiredMarker)) { sections.push(requiredSection.trim()); } - const appendixMarker = markdownSectionMarker(soulAppendix); + const appendixMarker = markdownSectionMarker(effectiveSoulAppendix); if ( filename === "SOUL.md" && - soulAppendix.trim() && + effectiveSoulAppendix.trim() && appendixMarker && !existing.includes(appendixMarker) ) { - sections.push(soulAppendix.trim()); + sections.push(effectiveSoulAppendix.trim()); } if (sections.length > 0) { fs.appendFileSync(filePath, `\n${sections.join("\n\n")}\n`, "utf-8"); @@ -1267,14 +1273,14 @@ export function seedAgentPersonaWorkspace( if (requiredMarker && !existing.includes(requiredMarker)) { sections.push(OFFICE_ARTISAN_ARTIFACT_BOUNDARY_SECTION.trim()); } - const appendixMarker = markdownSectionMarker(soulAppendix); + const appendixMarker = markdownSectionMarker(effectiveSoulAppendix); if ( filename === "SOUL.md" && - soulAppendix.trim() && + effectiveSoulAppendix.trim() && appendixMarker && !existing.includes(appendixMarker) ) { - sections.push(soulAppendix.trim()); + sections.push(effectiveSoulAppendix.trim()); } if (sections.length > 0) { fs.appendFileSync(filePath, `\n${sections.join("\n\n")}\n`, "utf-8"); @@ -1292,9 +1298,9 @@ export function seedAgentPersonaWorkspace( sections.push(workspaceSource.trim()); existing += `\n${workspaceSource.trim()}\n`; } - const appendixMarker = markdownSectionMarker(soulAppendix); - if (soulAppendix.trim() && appendixMarker && !existing.includes(appendixMarker)) { - sections.push(soulAppendix.trim()); + const appendixMarker = markdownSectionMarker(effectiveSoulAppendix); + if (effectiveSoulAppendix.trim() && appendixMarker && !existing.includes(appendixMarker)) { + sections.push(effectiveSoulAppendix.trim()); } if (sections.length > 0) { fs.appendFileSync(filePath, `\n${sections.join("\n\n")}\n`, "utf-8"); @@ -1304,14 +1310,14 @@ export function seedAgentPersonaWorkspace( continue; } - const appendixMarker = markdownSectionMarker(soulAppendix); + const appendixMarker = markdownSectionMarker(effectiveSoulAppendix); const shouldAppendSoulSection = filename === "SOUL.md" && - soulAppendix.trim() && + effectiveSoulAppendix.trim() && appendixMarker && !workspaceSource.includes(appendixMarker); const content = shouldAppendSoulSection - ? `${workspaceSource.trimEnd()}\n\n${soulAppendix.trim()}\n` + ? `${workspaceSource.trimEnd()}\n\n${effectiveSoulAppendix.trim()}\n` : `${workspaceSource.trimEnd()}\n`; fs.writeFileSync(filePath, content, "utf-8"); updatedFiles.push(filePath); @@ -1320,6 +1326,70 @@ export function seedAgentPersonaWorkspace( return [...new Set(updatedFiles)]; } +export function synchronizeAgentWindowsNodeInstructions( + config: AgentRosterConfig, + stateDir: string, + legacySoulAppendix: string, + mxcEnabled: boolean, + env: NodeJS.ProcessEnv = process.env, + homeDir = os.homedir(), + cwd = process.cwd(), +): { updatedFiles: string[]; rollback: () => void } { + const configuredIds = new Set(listConfiguredAgents(config).map((agent) => agent.id)); + const seen = new Set(); + const changes: Array<{ filePath: string; before: string; after: string }> = []; + for (const persona of AGENT_PERSONAS) { + if (!persona.workspaceFiles?.["SOUL.md"] || !configuredIds.has(persona.id)) continue; + const workspace = resolveAgentPersonaWorkspace(config, stateDir, persona, env, homeDir, cwd); + const filePath = path.join(workspace, "SOUL.md"); + const key = process.platform === "win32" ? filePath.toLowerCase() : filePath; + if (seen.has(key)) continue; + seen.add(key); + const before = fs.readFileSync(filePath, "utf-8"); + const after = updateWindowsNodeInstructions(before, legacySoulAppendix, mxcEnabled); + if (after !== before) changes.push({ filePath, before, after }); + } + + const applied: typeof changes = []; + const rollback = () => { + const errors: unknown[] = []; + for (let index = applied.length - 1; index >= 0; index -= 1) { + const change = applied[index]; + try { + if (fs.readFileSync(change.filePath, "utf-8") !== change.after) { + throw new Error(`Agent SOUL.md changed during rollback: ${change.filePath}`); + } + fs.writeFileSync(change.filePath, change.before, "utf-8"); + applied.splice(index, 1); + } catch (error) { + errors.push(error); + } + } + if (errors.length) throw new AggregateError(errors, "Failed to restore agent instructions"); + }; + try { + for (const change of changes) { + if (fs.readFileSync(change.filePath, "utf-8") !== change.before) { + throw new Error(`Agent SOUL.md changed during mode update: ${change.filePath}`); + } + fs.writeFileSync(change.filePath, change.after, "utf-8"); + applied.push(change); + } + } catch (error) { + try { + rollback(); + } catch (rollbackError) { + throw new AggregateError( + [error, rollbackError], + "Failed to update and restore agent instructions", + { cause: rollbackError }, + ); + } + throw error; + } + return { updatedFiles: changes.map((change) => change.filePath), rollback }; +} + function markdownSectionMarker(contents: string): string { return contents.split(/\r?\n/).find((line) => line.startsWith("## ")) ?? contents.trim(); } diff --git a/desktop/src/agent-workspaces-startup.test.ts b/desktop/src/agent-workspaces-startup.test.ts index 0c29bc9..876190d 100644 --- a/desktop/src/agent-workspaces-startup.test.ts +++ b/desktop/src/agent-workspaces-startup.test.ts @@ -1,12 +1,14 @@ -import { readFileSync } from "node:fs"; +import * as fs from "node:fs"; +import * as os from "node:os"; import * as path from "node:path"; import { createContext, runInContext } from "node:vm"; import ts from "typescript"; import { describe, expect, it, vi } from "vitest"; import { planDefaultWorkspaceFolderGrant } from "./agent-workspaces"; +import { updateWindowsNodeInstructions } from "./windows-node-command-instructions"; import { canonicalizeApprovedCwd } from "./windows-node-mxc"; -const source = readFileSync(path.join(__dirname, "main.ts"), "utf8"); +const source = fs.readFileSync(path.join(__dirname, "main.ts"), "utf8"); const ast = ts.createSourceFile("main.ts", source, ts.ScriptTarget.Latest, true); function mainFunction(name: string) { const declaration = ast.statements.find( @@ -15,6 +17,17 @@ function mainFunction(name: string) { if (!declaration) throw new Error(`Missing main function ${name}`); return declaration.getText(ast); } +function mainVariable(name: string) { + const statement = ast.statements.find( + (node) => + ts.isVariableStatement(node) && + node.declarationList.declarations.some( + (declaration) => ts.isIdentifier(declaration.name) && declaration.name.text === name, + ), + ); + if (!statement) throw new Error(`Missing main variable ${name}`); + return statement.getText(ast); +} const parent = "C:\\Users\\alice\\OpenClawWorkspaces"; function grantHarness() { @@ -121,6 +134,62 @@ describe("workspace startup wiring", () => { expect(seeder).toContain("resolveAgentPersonaWorkspace("); expect(seeder).not.toContain('path.join(stateDir, "workspace")'); expect(mainFunction("captureAgentWorkspace")).toContain('"BOOTSTRAP.md"'); + expect(startup).toContain("const mxcEnabledForInstructions = isWindowsNodeMxcDesired()"); + expect(startup).toContain("mxcEnabledForInstructions,"); + }); + + it("seeds and migrates the actual main SOUL for the current sandbox mode", () => { + const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "microclaw-main-soul-")); + try { + const context = createContext({ + exports: {} as { + seed?: ( + state: string, + config: object, + env: object, + cwd: string, + enabled: boolean, + ) => void; + defaultSoul?: string; + }, + fs, + path, + os, + updateWindowsNodeInstructions, + MAIN_PLATFORM_IDENTITY_SECTION: "## Platform Identity\n\nKeep the identity.", + resolveAgentPersonaWorkspace: () => workspace, + getAgentPersona: () => ({ id: "main" }), + console: { log: vi.fn(), warn: vi.fn() }, + }); + runInContext( + ts.transpileModule( + `${mainVariable("DEFAULT_SOUL_MD")} + ${mainVariable("DECLARE_ACCESS_SECTION")} + exports.seed = ${mainFunction("seedWorkspaceFiles")}; + exports.defaultSoul = DEFAULT_SOUL_MD;`, + { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }, + ).outputText, + context, + ); + const seed = context.exports.seed!; + const soulPath = path.join(workspace, "SOUL.md"); + seed(workspace, {}, {}, workspace, false); + expect(fs.readFileSync(soulPath, "utf-8")).not.toMatch(/\bMXC\b|\[declare-access\]/); + + fs.writeFileSync(soulPath, `${context.exports.defaultSoul}\n## User notes\nKeep these.\n`); + seed(workspace, {}, {}, workspace, false); + expect(fs.readFileSync(soulPath, "utf-8")).not.toMatch(/\bMXC\b|\[declare-access\]/); + seed(workspace, {}, {}, workspace, true); + expect(fs.readFileSync(soulPath, "utf-8")).toContain( + "## MXC filesystem and executable recovery", + ); + seed(workspace, {}, {}, workspace, false); + const off = fs.readFileSync(soulPath, "utf-8"); + expect(off).not.toMatch(/\bMXC\b|\[declare-access\]/); + expect(off).toContain("## User notes\nKeep these."); + } finally { + fs.rmSync(workspace, { recursive: true, force: true }); + } }); it("applies the same layout when adding an agent without creating per-agent grants", () => { @@ -132,5 +201,6 @@ describe("workspace startup wiring", () => { add.indexOf("captureAgentWorkspace("), ); expect(add).not.toContain("windowsNodeMxcFolders"); + expect(add).toContain("isWindowsNodeMxcDesired()"); }); }); diff --git a/desktop/src/main.ts b/desktop/src/main.ts index c082011..f1a8cfc 100644 --- a/desktop/src/main.ts +++ b/desktop/src/main.ts @@ -195,6 +195,7 @@ import { resolveAgentPersonaWorkspace, seedAgentPersonaWorkspace, seedAgentPersonaWorkspaces, + synchronizeAgentWindowsNodeInstructions, type AgentPersona, type AgentRosterConfig, } from "./agent-personas"; @@ -1834,6 +1835,7 @@ function seedWorkspaceFiles( config: AgentRosterConfig, gatewayEnvironment: NodeJS.ProcessEnv, cwd: string, + mxcEnabled: boolean, ): void { const workspaceDir = resolveAgentPersonaWorkspace( config, @@ -1846,11 +1848,9 @@ function seedWorkspaceFiles( const soulPath = path.join(workspaceDir, "SOUL.md"); if (fs.existsSync(soulPath)) { - // SOUL.md exists — ensure the declare-access section is present. - // This patches existing SOUL.md files from older versions that lack it. try { const existing = fs.readFileSync(soulPath, "utf-8"); - const updated = updateWindowsNodeInstructions(existing, DECLARE_ACCESS_SECTION); + const updated = updateWindowsNodeInstructions(existing, DECLARE_ACCESS_SECTION, mxcEnabled); if (updated !== existing) { fs.writeFileSync(soulPath, updated, "utf-8"); console.log("[seed] Updated generated Windows Node command instructions"); @@ -1865,7 +1865,7 @@ function seedWorkspaceFiles( } fs.writeFileSync( soulPath, - updateWindowsNodeInstructions(DEFAULT_SOUL_MD, DECLARE_ACCESS_SECTION), + updateWindowsNodeInstructions(DEFAULT_SOUL_MD, DECLARE_ACCESS_SECTION, mxcEnabled), "utf-8", ); console.log(`[seed] Created default SOUL.md at ${soulPath}`); @@ -3123,9 +3123,23 @@ async function changeWindowsNodeMxcMode(params: { }, release: async () => { assertCurrent(requestedMode); - releaseWindowsNodeMxcIngress(generation); - windowsNodeMxcActivationInProgress = false; - setWindowsNodeMxcLifecycleState(requestedMode === "full" ? "active" : "idle"); + const instructions = synchronizeWindowsNodeInstructionsForMode(requestedMode === "full"); + try { + releaseWindowsNodeMxcIngress(generation); + windowsNodeMxcActivationInProgress = false; + setWindowsNodeMxcLifecycleState(requestedMode === "full" ? "active" : "idle"); + } catch (error) { + try { + instructions.rollback(); + } catch (rollbackError) { + throw new AggregateError( + [error, rollbackError], + "Sandbox mode change and agent instruction rollback failed", + { cause: rollbackError }, + ); + } + throw error; + } }, failClosed: async (error) => { closeWindowsNodeMxcIngress(); @@ -3142,7 +3156,11 @@ async function changeWindowsNodeMxcMode(params: { }, }), { - beforeStart: () => beginWindowsNodeMxcLifecycleOperation(requestedMode === "off"), + beforeStart: () => { + if (agentRosterChangeInProgress) + throw new Error("Wait for the current agent roster change to finish"); + beginWindowsNodeMxcLifecycleOperation(requestedMode === "off"); + }, afterSettled: () => { if (!locked && windowsNodeMxcLifecycleState === "validating") setWindowsNodeMxcLifecycleState(previousMode === "off" ? "idle" : "active"); @@ -4704,6 +4722,7 @@ function seedSpecialistAgentWorkspaces( stateDir: string, entryPath: string, gatewayEnvironment: Record, + mxcEnabled: boolean, ): string[] { const seededFiles = seedAgentPersonaWorkspaces( config, @@ -4713,6 +4732,7 @@ function seedSpecialistAgentWorkspaces( os.homedir(), path.dirname(entryPath), DECLARE_ACCESS_SECTION, + mxcEnabled, ); if (seededFiles.length > 0) { console.log(`[seed] Created specialist agent workspace files: ${seededFiles.join(", ")}`); @@ -4720,6 +4740,30 @@ function seedSpecialistAgentWorkspaces( return seededFiles; } +function synchronizeWindowsNodeInstructionsForMode(mxcEnabled: boolean): { + updatedFiles: string[]; + rollback: () => void; +} { + const config = readConfig(); + if (!config) throw new Error("OpenClaw configuration is unavailable"); + const stateDir = getOpenClawStateDir(); + const result = synchronizeAgentWindowsNodeInstructions( + config, + stateDir, + DECLARE_ACCESS_SECTION, + mxcEnabled, + loadGatewayEnvironment(stateDir), + os.homedir(), + path.dirname(resolveOpenClawEntry()), + ); + if (result.updatedFiles.length > 0) { + console.log( + `[seed] Updated Windows Node guidance in ${result.updatedFiles.length} workspace(s)`, + ); + } + return result; +} + interface WorkspaceSnapshot { directory: string; directoryExisted: boolean; @@ -4917,6 +4961,7 @@ async function addCatalogAgent( os.homedir(), path.dirname(entryPath), DECLARE_ACCESS_SECTION, + isWindowsNodeMxcDesired(), ); assertAgentRosterHotReloadAvailable( config, @@ -6346,17 +6391,20 @@ async function runGatewayStartup( } if (preparedPersonas && !externallyManagedGateway) { agentSkillTransactionPending = true; + const mxcEnabledForInstructions = isWindowsNodeMxcDesired(); seedWorkspaceFiles( stateDir, preparedPersonas.config, gatewayEnvironment, path.dirname(entryPath), + mxcEnabledForInstructions, ); seedSpecialistAgentWorkspaces( preparedPersonas.config, stateDir, entryPath, gatewayEnvironment, + mxcEnabledForInstructions, ); } } catch (error) { diff --git a/desktop/src/windows-node-command-instructions.test.ts b/desktop/src/windows-node-command-instructions.test.ts index 4fdcfbd..578c881 100644 --- a/desktop/src/windows-node-command-instructions.test.ts +++ b/desktop/src/windows-node-command-instructions.test.ts @@ -4,6 +4,8 @@ import { WINDOWS_NODE_ACCESS_INSTRUCTIONS, WINDOWS_NODE_GIT_INSTRUCTIONS, WINDOWS_NODE_MEMORY_INSTRUCTIONS, + WINDOWS_NODE_MXC_FILESYSTEM_INSTRUCTIONS, + WINDOWS_NODE_MXC_POWERSHELL_OPERATIONS_INSTRUCTIONS, WINDOWS_NODE_PERMISSION_DENIED_INSTRUCTIONS, WINDOWS_NODE_POWERSHELL_QUOTING_INSTRUCTIONS, WINDOWS_NODE_POWERSHELL_SCRATCH_INSTRUCTIONS, @@ -27,17 +29,66 @@ Windows Node decides whether a command can be remembered. CMD built-ins and inline PowerShell generally require one-use approval; do not rewrite commands to bypass this. MXC folder grants remain independent of command consent. `; + const previousMxcTransport = `## Windows Node command transport - it("replaces a recognized generated section without changing surrounding content", () => { - const source = `# Personality\n\nKeep my voice.\n\n${legacy}\n## Custom guidance\n\nKeep this too.\n`; - const updated = updateWindowsNodeInstructions(source, legacy); +The exec tool uses OpenClaw's Windows Node transport: cmd.exe /d /s /c. +Use CMD syntax, not bare PowerShell cmdlets. For example, use \`dir\`, \`type\`, +or \`git status\`. Invoke powershell.exe explicitly when PowerShell is necessary. +Command consent applies to exec in both regular and MXC modes. Gateway-native +file tools remain available in both modes, but run outside MXC and bypass exec +consent and MXC folder grants. Use an appropriate native file tool when its +boundary is acceptable; use contained exec when the user requests containment. +Route by the tools available now, not by a previous mode or the last successful +action. Do not retry a denied or failed native operation through exec unless the +user authorizes that fallback. +Windows Node decides whether a command can be remembered. CMD built-ins and +quoted or dynamic PowerShell may require one-use approval. Never change an +approved command to bypass consent. MXC folder grants remain independent. +`; + const previousGeneratedAccess = `## Pre-declaring File System Access - expect(updated).toContain("# Personality\n\nKeep my voice."); - expect(updated).toContain("## Custom guidance\n\nKeep this too."); - expect(updated).not.toContain("Get-ChildItem"); - expect(updated).toContain(WINDOWS_NODE_ACCESS_INSTRUCTIONS.trim()); - expect(updateWindowsNodeInstructions(updated, legacy)).toBe(updated); - }); +For exec commands that access files outside the workspace in MXC mode, put +a declaration on the first line and the actual CMD command on the next line. +The host removes the declaration before execution. Use literal absolute Windows +directory paths, with ro for reading or rw for creating, changing, or deleting. +Do not use variables in declarations or submit a declaration without a command. + +MXC can switch live. In Off mode, do not add declarations or request MXC +folder grants; host execution remains subject to command-consent settings. + +\`\`\` +REM [declare-access]ro:C:\\Users\\alice\\Desktop[/declare-access] +dir "C:\\Users\\alice\\Desktop" +\`\`\` + +\`\`\` +REM [declare-access]rw:C:\\Users\\alice\\Desktop;rw:C:\\Users\\alice\\Documents[/declare-access] +move "C:\\Users\\alice\\Desktop\\report.xlsx" "C:\\Users\\alice\\Documents\\" +\`\`\` + +Declare only the directories actually needed, never a drive root or all users. +A declaration requests access; it does not grant it. Missing MXC folder grants +and command approval are presented together in one prompt. +`; + + it.each(["\n", "\r\n"])( + "replaces a recognized generated section without changing surrounding content", + (lineEnding) => { + const source = + `# Personality\n\nKeep my voice.\n\n${legacy}\n## Custom guidance\n\nKeep this too.\n`.replace( + /\n/g, + lineEnding, + ); + const updated = updateWindowsNodeInstructions(source, legacy); + const normalized = updated.replace(/\r\n/g, "\n"); + + expect(normalized).toContain("# Personality\n\nKeep my voice."); + expect(normalized).toContain("## Custom guidance\n\nKeep this too."); + expect(updated).not.toContain("Get-ChildItem"); + expect(normalized).toContain(WINDOWS_NODE_ACCESS_INSTRUCTIONS.trim()); + expect(updateWindowsNodeInstructions(updated, legacy)).toBe(updated); + }, + ); it("preserves a customized access section and adds the transport instructions once", () => { const source = "## Pre-declaring File System Access\n\nMy custom rules.\n"; @@ -56,12 +107,77 @@ to bypass this. MXC folder grants remain independent of command consent. expect(updateWindowsNodeInstructions(updated, legacy)).toBe(updated); }); + it("adds only mode-independent instructions when MXC is off", () => { + const updated = updateWindowsNodeInstructions("# My agent\n", legacy, false); + + expect(updated).toContain("## Memory recall before filesystem tools"); + expect(updated).toContain("## Windows Node command transport"); + expect(updated).toContain("## PowerShell command quoting"); + expect(updated).not.toMatch(/\bMXC\b|\[declare-access\]/); + expect(updateWindowsNodeInstructions(updated, legacy, false)).toBe(updated); + }); + + it.each(["\n", "\r\n"])( + "removes generated MXC guidance when disabled and restores it when enabled", + (lineEnding) => { + const source = + `# My agent\n\n${previousGeneratedAccess}\n${previousMxcTransport}\n## Notes\nKeep these.\n`.replace( + /\n/g, + lineEnding, + ); + const off = updateWindowsNodeInstructions(source, legacy, false); + expect(off).toContain(`## Notes${lineEnding}Keep these.`); + expect(off).not.toMatch(/\bMXC\b|\[declare-access\]/); + if (lineEnding === "\r\n") expect(off.replace(/\r\n/g, "")).not.toContain("\n"); + expect(updateWindowsNodeInstructions(off, legacy, false)).toBe(off); + + const on = updateWindowsNodeInstructions(off, legacy, true); + expect(on).toContain("## MXC filesystem and executable recovery"); + expect(on).toContain("## PowerShell filesystem operations in MXC"); + expect(on).toContain(`## Notes${lineEnding}Keep these.`); + expect(on.match(/## Windows Node command transport/g)).toHaveLength(1); + if (lineEnding === "\r\n") expect(on.replace(/\r\n/g, "")).not.toContain("\n"); + expect(updateWindowsNodeInstructions(on, legacy, true)).toBe(on); + + const offAgain = updateWindowsNodeInstructions(on, legacy, false); + expect(offAgain).not.toMatch(/\bMXC\b|\[declare-access\]/); + expect(offAgain).toContain(`## Notes${lineEnding}Keep these.`); + expect(updateWindowsNodeInstructions(offAgain, legacy, false)).toBe(offAgain); + }, + ); + + it("preserves user-modified guidance when MXC is disabled", () => { + const edited = WINDOWS_NODE_MXC_FILESYSTEM_INSTRUCTIONS.replace( + "When MXC is On", + "My custom rule: when MXC is On", + ); + const appended = `${WINDOWS_NODE_POWERSHELL_SCRATCH_INSTRUCTIONS.trim()}\n\nMy own note.\n`; + const source = `# My agent\n\n${edited}\n${appended}\n## Notes\nKeep these.\n`; + const updated = updateWindowsNodeInstructions(source, legacy, false); + + expect(updated).toContain(edited.trim()); + expect(updated).toContain(appended.trim()); + expect(updated).toContain("## Notes\nKeep these."); + expect(updateWindowsNodeInstructions(updated, legacy, false)).toBe(updated); + }); + + it("removes the original generated access section when starting in Off mode", () => { + const updated = updateWindowsNodeInstructions( + `# My agent\n\n${legacy}\n## Notes\nKeep these.\n`, + legacy, + false, + ); + expect(updated).not.toContain("Legacy PowerShell examples."); + expect(updated).not.toMatch(/\bMXC\b|\[declare-access\]/); + expect(updated).toContain("## Notes\nKeep these."); + }); + it("upgrades generated access guidance to distinguish Off mode without changing user notes", () => { const previous = WINDOWS_NODE_ACCESS_INSTRUCTIONS.replace( "MXC can switch live. In Off mode, do not add declarations or request MXC\n" + "folder grants; host execution remains subject to command-consent settings.\n\n", "", - ); + ).replace('type "C:\\Users\\alice\\Desktop\\notes.txt"', 'dir "C:\\Users\\alice\\Desktop"'); const updated = updateWindowsNodeInstructions( `# Agent\n\n${previous}\n## Notes\nKeep these.\n`, legacy, @@ -72,6 +188,103 @@ to bypass this. MXC folder grants remain independent of command consent. expect(updateWindowsNodeInstructions(updated, legacy)).toBe(updated); }); + it.each([ + { hasOffGuidance: true, lineEnding: "\n" }, + { hasOffGuidance: false, lineEnding: "\n" }, + { hasOffGuidance: true, lineEnding: "\r\n" }, + { hasOffGuidance: false, lineEnding: "\r\n" }, + ])( + "upgrades the previously generated instructions without changing user notes (%o)", + ({ hasOffGuidance, lineEnding }) => { + const access = hasOffGuidance + ? previousGeneratedAccess + : previousGeneratedAccess.replace( + "MXC can switch live. In Off mode, do not add declarations or request MXC\n" + + "folder grants; host execution remains subject to command-consent settings.\n\n", + "", + ); + const original = + `# My agent\n\n${access}\n${previousMxcTransport}\n## Notes\nKeep these.\n`.replace( + /\n/g, + lineEnding, + ); + const updated = updateWindowsNodeInstructions(original, legacy); + + expect(updated).toContain(`## Notes${lineEnding}Keep these.`); + expect(updated).toContain('type "C:\\Users\\alice\\Desktop\\notes.txt"'); + expect(updated).not.toContain('dir "C:\\Users\\alice\\Desktop"'); + expect(updated).not.toContain("For example, use `dir`, `type`"); + const normalized = updated.replace(/\r\n/g, "\n"); + expect(normalized).toContain(WINDOWS_NODE_MXC_FILESYSTEM_INSTRUCTIONS.trim()); + expect(normalized).toContain(WINDOWS_NODE_MXC_POWERSHELL_OPERATIONS_INSTRUCTIONS.trim()); + expect(updated.match(/## Windows Node command transport/g)).toHaveLength(1); + expect(updated.match(/## MXC filesystem and executable recovery/g)).toHaveLength(1); + expect(updated.match(/## PowerShell filesystem operations in MXC/g)).toHaveLength(1); + expect(updateWindowsNodeInstructions(updated, legacy)).toBe(updated); + }, + ); + + it("adds recovery guidance without replacing customized access and transport sections", () => { + const customizedAccess = previousGeneratedAccess.replace( + "Declare only the directories actually needed", + "My custom rule: declare only the directories actually needed", + ); + const customizedTransport = previousMxcTransport.replace( + "Use CMD syntax", + "My custom rule: use CMD syntax", + ); + const source = `${customizedAccess}\n${customizedTransport}\n## Notes\nKeep these.\n`; + const updated = updateWindowsNodeInstructions(source, legacy); + + expect(updated).toContain(customizedAccess.trim()); + expect(updated).toContain(customizedTransport.trim()); + expect(updated).toContain("## Notes\nKeep these."); + expect(updated).toContain(WINDOWS_NODE_MXC_FILESYSTEM_INSTRUCTIONS.trim()); + expect(updated).toContain(WINDOWS_NODE_MXC_POWERSHELL_OPERATIONS_INSTRUCTIONS.trim()); + expect(updateWindowsNodeInstructions(updated, legacy)).toBe(updated); + }); + + it("guides Gateway tool routing, scoped executable discovery, and existing declarations", () => { + const guidance = updateWindowsNodeInstructions("# My agent\n", legacy); + + expect(guidance).toMatch(/Gateway-native file tools: use `ls`.*`read`/); + expect(guidance).toContain("run outside MXC"); + expect(guidance).toContain("bypass a denied operation or a user's requirement for containment"); + expect(guidance).toMatch(/set `workdir` to an existing approved directory/); + expect(guidance).toContain("does not fix every metadata failure"); + expect(guidance).toContain("a contained `where` can miss a program"); + expect(guidance).toContain("C:\\Program Files"); + expect(guidance).toContain("C:\\Program Files (x86)"); + expect(guidance).toContain("Inspect the candidate folder to confirm the"); + expect(guidance).toContain("follow listing pagination"); + expect(guidance).toContain("smallest existing, permitted installation"); + expect(guidance).toContain("Discovery is not authorization"); + expect(guidance).toContain("must be an existing local directory"); + expect(guidance).toContain("declare the smallest appropriate existing parent as rw"); + expect(guidance).toContain("Never declare a drive root or protected folder"); + expect(guidance).toMatch(/check the declared directories as well as\s+`workdir`/); + }); + + it("guides safe PowerShell splitting and same-invocation initialization", () => { + const guidance = updateWindowsNodeInstructions("# My agent\n", legacy); + + for (const command of ["Remove-Item", "Move-Item", "Rename-Item"]) { + expect(guidance).toContain(`\`${command}\``); + } + expect(guidance).toContain("prefer one operation"); + expect(guidance).toContain("when splitting preserves the requested behavior"); + expect(guidance).toContain("literal absolute paths and `-LiteralPath`"); + expect(guidance).toMatch( + /rw entries covering the source and destination even if\s+their existing directories are already approved or in the workspace/, + ); + expect(guidance).toContain("initializer matches each target against these declarations"); + expect(guidance).toContain("not all command forms qualify"); + expect(guidance).toContain("Do not split a complex script"); + expect(guidance).toContain("initialization and the operation in the same correctly quoted"); + expect(guidance).toContain("Initialization in a separate exec does not"); + expect(guidance).toContain("fresh approval"); + }); + it("upgrades the prior generated transport guidance without changing user notes", () => { const source = `${legacy}\n${previousTransport}\n## User notes\n\nPreserve my instructions.\n`; const updated = updateWindowsNodeInstructions(source, legacy); @@ -111,29 +324,38 @@ to bypass this. MXC folder grants remain independent of command consent. ); }); - it("removes the previous generated deletion workaround while preserving adjacent user notes", () => { - const previous = - "## PowerShell deletion in MXC\n\n" + - "When using Remove-Item in MXC mode, include a scoped filesystem-drive setup in\n" + - "your own PowerShell script before the deletion. This avoids a PowerShell provider\n" + - "initialization failure without changing the OpenClaw command transport. For a\n" + - "literal file, for example:\n\n" + - "```\nREM [declare-access]rw:C:\\work[/declare-access]\n" + - "powershell.exe -NoProfile -Command \"New-PSDrive -Name MicroClawCwd -PSProvider FileSystem -Root ([Environment]::CurrentDirectory) -Scope Script -ErrorAction Stop | Out-Null; Set-Location -LiteralPath 'MicroClawCwd:\\' -ErrorAction Stop; Remove-Item -LiteralPath 'C:\\work\\notes.txt' -Force -ErrorAction Stop\"\n" + - "```\n\n" + - "Declare only the folder needed for the requested operation. Do not broaden\n" + - "folder grants or add recursive deletion unless the user requested it. Keep the\n" + - "script quotes and escape values correctly for CMD and PowerShell. This compound\n" + - "command may require one-use approval; do not alter it to bypass consent.\n"; - const updated = updateWindowsNodeInstructions( - `# My agent\n\n${previous}\n## My notes\nKeep these.\n`, - legacy, - ); - expect(updated).toContain("## My notes\nKeep these."); - expect(updated).not.toContain("## PowerShell deletion in MXC"); - expect(updated).toContain(WINDOWS_NODE_POWERSHELL_SCRATCH_INSTRUCTIONS.trim()); - expect(updateWindowsNodeInstructions(updated, legacy)).toBe(updated); - }); + it.each(["\n", "\r\n"])( + "removes the previous generated deletion workaround while preserving adjacent user notes", + (lineEnding) => { + const previous = + "## PowerShell deletion in MXC\n\n" + + "When using Remove-Item in MXC mode, include a scoped filesystem-drive setup in\n" + + "your own PowerShell script before the deletion. This avoids a PowerShell provider\n" + + "initialization failure without changing the OpenClaw command transport. For a\n" + + "literal file, for example:\n\n" + + "```\nREM [declare-access]rw:C:\\work[/declare-access]\n" + + "powershell.exe -NoProfile -Command \"New-PSDrive -Name MicroClawCwd -PSProvider FileSystem -Root ([Environment]::CurrentDirectory) -Scope Script -ErrorAction Stop | Out-Null; Set-Location -LiteralPath 'MicroClawCwd:\\' -ErrorAction Stop; Remove-Item -LiteralPath 'C:\\work\\notes.txt' -Force -ErrorAction Stop\"\n" + + "```\n\n" + + "Declare only the folder needed for the requested operation. Do not broaden\n" + + "folder grants or add recursive deletion unless the user requested it. Keep the\n" + + "script quotes and escape values correctly for CMD and PowerShell. This compound\n" + + "command may require one-use approval; do not alter it to bypass consent.\n"; + const source = `# My agent\n\n${previous}\n## My notes\nKeep these.\n`.replace( + /\n/g, + lineEnding, + ); + const updated = updateWindowsNodeInstructions(source, legacy); + expect(updated).toContain(`## My notes${lineEnding}Keep these.`); + expect(updated).not.toContain("## PowerShell deletion in MXC"); + expect(updated.replace(/\r\n/g, "\n")).toContain( + WINDOWS_NODE_POWERSHELL_SCRATCH_INSTRUCTIONS.trim(), + ); + expect(updateWindowsNodeInstructions(updated, legacy)).toBe(updated); + const off = updateWindowsNodeInstructions(source, legacy, false); + expect(off).toContain(`## My notes${lineEnding}Keep these.`); + expect(off).not.toMatch(/\bMXC\b|\[declare-access\]/); + }, + ); it("preserves customized deletion guidance and does not add a duplicate", () => { const source = "## PowerShell deletion in MXC\n\nMy custom deletion instructions.\n"; diff --git a/desktop/src/windows-node-command-instructions.ts b/desktop/src/windows-node-command-instructions.ts index 6443dd8..8b142cc 100644 --- a/desktop/src/windows-node-command-instructions.ts +++ b/desktop/src/windows-node-command-instructions.ts @@ -17,6 +17,16 @@ than claiming there are no memories or silently falling back to exec. Reading memory does not authorize editing it or changing any folder permissions. `; +const WINDOWS_NODE_OFF_MEMORY_INSTRUCTIONS = WINDOWS_NODE_MEMORY_INSTRUCTIONS.replace( + "In both regular and MXC modes, use memory tools", + "Use memory tools", +).replace( + "sources and session privacy rules. It runs in the Gateway, independently of MXC\n" + + "folder grants; it is not general filesystem permission.", + "sources and session privacy rules. It runs in the Gateway; it is not general\n" + + "filesystem permission.", +); + const PRE_MEMORY_TRANSPORT_INSTRUCTIONS = `## Windows Node command transport The exec tool uses OpenClaw's Windows Node transport: cmd.exe /d /s /c. @@ -41,7 +51,7 @@ const PRE_RESTORED_FILE_ROUTING_TRANSPORT_INSTRUCTIONS = PRE_MEMORY_TRANSPORT_IN "native operation through exec unless the user authorizes that fallback.", ); -const WINDOWS_NODE_TRANSPORT_INSTRUCTIONS = `## Windows Node command transport +const PREVIOUS_MXC_TRANSPORT_INSTRUCTIONS = `## Windows Node command transport The exec tool uses OpenClaw's Windows Node transport: cmd.exe /d /s /c. Use CMD syntax, not bare PowerShell cmdlets. For example, use \`dir\`, \`type\`, @@ -58,12 +68,76 @@ quoted or dynamic PowerShell may require one-use approval. Never change an approved command to bypass consent. MXC folder grants remain independent. `; +const WINDOWS_NODE_TRANSPORT_INSTRUCTIONS = PREVIOUS_MXC_TRANSPORT_INSTRUCTIONS.replace( + "Use CMD syntax, not bare PowerShell cmdlets. For example, use `dir`, `type`,\n" + + "or `git status`. Invoke powershell.exe explicitly when PowerShell is necessary.", + "Use CMD syntax, not bare PowerShell cmdlets. For example, use `type` or\n" + + "`git status`. Invoke powershell.exe explicitly when PowerShell is necessary.", +); + +const WINDOWS_NODE_OFF_TRANSPORT_INSTRUCTIONS = `## Windows Node command transport + +The exec tool uses OpenClaw's Windows Node transport: cmd.exe /d /s /c. +Use CMD syntax, not bare PowerShell cmdlets. For example, use \`type\` or +\`git status\`. Invoke powershell.exe explicitly when PowerShell is necessary. +Command consent applies to exec. Gateway-native file tools run outside exec +and bypass command consent. Use an appropriate native file tool when its +boundary is acceptable; choose exec for shell workflows or operations without +a suitable native tool. Route by the tools available now, not by a previous +mode or the last successful action. Do not retry a denied or failed native +operation through exec unless the user authorizes that fallback. +Windows Node decides whether a command can be remembered. CMD built-ins and +quoted or dynamic PowerShell may require one-use approval. Never change an +approved command to bypass consent. +`; + const PRE_FILE_ROUTING_TRANSPORT_INSTRUCTIONS = PRE_MEMORY_TRANSPORT_INSTRUCTIONS.replace( "native file tools are unavailable; choose an exec command for file operations.", "native file tools are unavailable; use scoped memory tools for memory recall\n" + "and contained exec for other file operations.", ); +export const WINDOWS_NODE_MXC_FILESYSTEM_INSTRUCTIONS = `## MXC filesystem and executable recovery + +When MXC is On and host-side access is acceptable, prefer available +Gateway-native file tools: use \`ls\` to list directories and \`read\` to read +files instead of running directory-listing commands through exec. Gateway tools +run outside MXC and do not use its folder grants or command consent. Do not use +them to bypass a denied operation or a user's requirement for containment. +If they are unavailable or their boundary is unacceptable, keep the operation +contained and report failures rather than silently switching. + +For exec, set \`workdir\` to an existing approved directory instead of using +\`cd /d\` where practical. CMD \`dir\` can fail because of volume-root +metadata, and absolute \`cd\` has also failed in approved directories. Setting +\`workdir\` avoids the extra \`cd\` but does not fix every metadata failure. + +If an executable such as \`node\` or \`python\` is not found, do not assume +it is uninstalled: a contained \`where\` can miss a program whose folder is not +granted even when PATH is correct. When Gateway \`ls\` is available and its +host-side boundary is acceptable, inspect relevant installation locations, +such as \`C:\\Program Files\`, \`C:\\Program Files (x86)\`, user-local or +otherwise known locations. Inspect the candidate folder to confirm the +executable and follow listing pagination when needed. Do not recursively scan +whole drives or profiles. If the location cannot be established, ask for it +or report the limitation instead of guessing or requesting broad access. +For contained execution, declare the smallest existing, permitted installation +directory as ro, submit the actual command for normal approval, and use the +discovered executable's absolute path. Discovery is not authorization. A PATH +issue or metadata failure can remain after approval; do not broaden access +repeatedly or bypass a denial. + +A [declare-access] path must be an existing local directory, not a destination +the command will create. For a new child such as a Git clone destination, +declare the smallest appropriate existing parent as rw and obtain normal +approval if needed. If the immediate parent is missing, use an appropriately +scoped existing ancestor. Never declare a drive root or protected folder; if no +appropriate ancestor can be approved, ask for another location or report the +limitation. Do not create a directory outside MXC just to obtain a grant. +If \`cwd-not-found\` occurs, check the declared directories as well as +\`workdir\`; a missing declaration can produce the same error. +`; + export const WINDOWS_NODE_POWERSHELL_QUOTING_INSTRUCTIONS = `## PowerShell command quoting For a simple PowerShell command, prefer leaving the entire -Command script @@ -88,6 +162,34 @@ initialized script as a new command for fresh consent. Do not silently change an approved command or broaden folder grants to work around the error. `; +export const WINDOWS_NODE_MXC_POWERSHELL_OPERATIONS_INSTRUCTIONS = `## PowerShell filesystem operations in MXC + +For \`Remove-Item\`, \`Move-Item\`, and \`Rename-Item\`, prefer one operation +per exec when splitting preserves the requested behavior. Use the full cmdlet +name, literal absolute paths and \`-LiteralPath\` where supported; for +\`Rename-Item\`, use a literal new name. For MXC On, include explicit +\`[declare-access]\` rw entries covering the source and destination even if +their existing directories are already approved or in the workspace: the +initializer matches each target against these declarations. A declaration is +not a grant; missing access and command consent require normal approval. +Avoid aliases, variables, wildcards, loops, pipelines, and compound scripts for +these simple operations. +For example, only when the user requested this deletion: + +\`\`\` +REM [declare-access]rw:C:\\work[/declare-access] +powershell.exe -NoProfile -Command Remove-Item -LiteralPath 'C:\\work\\old.txt' +\`\`\` + +The host can initialize the PowerShell filesystem provider for eligible exact +literal commands; not all command forms qualify. Do not split a complex script +if doing so changes its semantics. If it needs provider initialization, +include both the initialization and the operation in the same correctly quoted +PowerShell script, as described in PowerShell in MXC scratch, and submit the +complete command for fresh approval. Initialization in a separate exec does not +carry over. Do not change the requested effects or bypass consent. +`; + const PREVIOUS_MXC_POWERSHELL_DELETE_INSTRUCTIONS = `## PowerShell deletion in MXC When using Remove-Item in MXC mode, include a scoped filesystem-drive setup in @@ -108,10 +210,12 @@ command may require one-use approval; do not alter it to bypass consent. export const WINDOWS_NODE_SHELL_INSTRUCTIONS = `${WINDOWS_NODE_MEMORY_INSTRUCTIONS} ${WINDOWS_NODE_TRANSPORT_INSTRUCTIONS} +${WINDOWS_NODE_MXC_FILESYSTEM_INSTRUCTIONS} ${WINDOWS_NODE_POWERSHELL_QUOTING_INSTRUCTIONS} -${WINDOWS_NODE_POWERSHELL_SCRATCH_INSTRUCTIONS}`; +${WINDOWS_NODE_POWERSHELL_SCRATCH_INSTRUCTIONS} +${WINDOWS_NODE_MXC_POWERSHELL_OPERATIONS_INSTRUCTIONS}`; -const WINDOWS_NODE_ACCESS_SECTION = `## Pre-declaring File System Access +const PREVIOUS_WINDOWS_NODE_ACCESS_SECTION = `## Pre-declaring File System Access For exec commands that access files outside the workspace in MXC mode, put a declaration on the first line and the actual CMD command on the next line. @@ -137,7 +241,12 @@ A declaration requests access; it does not grant it. Missing MXC folder grants and command approval are presented together in one prompt. `; -const PREVIOUS_WINDOWS_NODE_ACCESS_SECTION = WINDOWS_NODE_ACCESS_SECTION.replace( +const WINDOWS_NODE_ACCESS_SECTION = PREVIOUS_WINDOWS_NODE_ACCESS_SECTION.replace( + 'dir "C:\\Users\\alice\\Desktop"', + 'type "C:\\Users\\alice\\Desktop\\notes.txt"', +); + +const LEGACY_WINDOWS_NODE_ACCESS_SECTION = PREVIOUS_WINDOWS_NODE_ACCESS_SECTION.replace( "MXC can switch live. In Off mode, do not add declarations or request MXC\n" + "folder grants; host execution remains subject to command-consent settings.\n\n", "", @@ -206,13 +315,61 @@ const PREVIOUS_TRANSPORT_INSTRUCTIONS_SHORT_GRANT_COPY = "MXC folder grants remain independent.", ); -export function updateWindowsNodeInstructions(content: string, legacySection: string): string { - let updated = content - .replace(`${PREVIOUS_MXC_POWERSHELL_DELETE_INSTRUCTIONS.trim()}\n\n`, "") - .replace(PREVIOUS_MXC_POWERSHELL_DELETE_INSTRUCTIONS.trim(), "") - .replace(PREVIOUS_WINDOWS_NODE_ACCESS_SECTION.trim(), WINDOWS_NODE_ACCESS_SECTION.trim()); +function replaceGeneratedSection(content: string, previous: string, replacement: string): string { + const before = previous.trim(); + const after = replacement.trim(); + if (!before) return content; + let updated = content; + for (const lineEnding of ["\n", "\r\n"]) { + const candidate = before.replace(/\n/g, lineEnding); + const next = after.replace(/\n/g, lineEnding); + let cursor = 0; + while (true) { + const start = updated.indexOf(candidate, cursor); + if (start < 0) break; + const end = start + candidate.length; + const following = updated.slice(end).trimStart(); + if ( + (start > 0 && updated[start - 1] !== "\n") || + (following && !/^#{1,2}(?:\s|$)/.test(following)) + ) { + cursor = end; + continue; + } + const prefix = updated.slice(0, start); + const suffix = updated.slice(end); + if (next) { + updated = prefix + next + suffix; + cursor = prefix.length + next.length; + } else if (!prefix.trim()) { + updated = suffix.replace(/^(?:[ \t]*\r?\n)+/, ""); + cursor = 0; + } else if (!suffix.trim()) { + updated = prefix.replace(/(?:\r?\n)+$/, lineEnding); + cursor = updated.length; + } else { + updated = prefix + suffix.replace(/^(?:[ \t]*\r?\n)+/, ""); + cursor = prefix.length; + } + } + } + return updated; +} + +export function updateWindowsNodeInstructions( + content: string, + legacySection: string, + mxcEnabled = true, +): string { + let updated = replaceGeneratedSection(content, PREVIOUS_MXC_POWERSHELL_DELETE_INSTRUCTIONS, ""); + for (const previous of [ + LEGACY_WINDOWS_NODE_ACCESS_SECTION, + PREVIOUS_WINDOWS_NODE_ACCESS_SECTION, + ]) { + updated = replaceGeneratedSection(updated, previous, WINDOWS_NODE_ACCESS_SECTION); + } const legacy = legacySection.trim(); - if (legacy && updated.includes(legacy)) { + if (legacy && (updated.includes(legacy) || updated.includes(legacy.replace(/\n/g, "\r\n")))) { const replacements = [WINDOWS_NODE_ACCESS_SECTION.trim()]; if (!updated.includes("## Permission-denied recovery in MXC")) { replacements.push(WINDOWS_NODE_PERMISSION_DENIED_INSTRUCTIONS.trim()); @@ -226,13 +383,19 @@ export function updateWindowsNodeInstructions(content: string, legacySection: st if (!updated.includes("## Windows Node command transport")) { replacements.push(WINDOWS_NODE_TRANSPORT_INSTRUCTIONS.trim()); } + if (!updated.includes("## MXC filesystem and executable recovery")) { + replacements.push(WINDOWS_NODE_MXC_FILESYSTEM_INSTRUCTIONS.trim()); + } if (!updated.includes("## PowerShell command quoting")) { replacements.push(WINDOWS_NODE_POWERSHELL_QUOTING_INSTRUCTIONS.trim()); } if (!updated.includes("## PowerShell in MXC scratch")) { replacements.push(WINDOWS_NODE_POWERSHELL_SCRATCH_INSTRUCTIONS.trim()); } - updated = updated.replace(legacy, replacements.join("\n\n")); + if (!updated.includes("## PowerShell filesystem operations in MXC")) { + replacements.push(WINDOWS_NODE_MXC_POWERSHELL_OPERATIONS_INSTRUCTIONS.trim()); + } + updated = replaceGeneratedSection(updated, legacy, replacements.join("\n\n")); } for (const previous of [ PREVIOUS_TRANSPORT_INSTRUCTIONS, @@ -241,11 +404,16 @@ export function updateWindowsNodeInstructions(content: string, legacySection: st PRE_MEMORY_TRANSPORT_INSTRUCTIONS, PRE_FILE_ROUTING_TRANSPORT_INSTRUCTIONS, PRE_RESTORED_FILE_ROUTING_TRANSPORT_INSTRUCTIONS, + PREVIOUS_MXC_TRANSPORT_INSTRUCTIONS, + WINDOWS_NODE_OFF_TRANSPORT_INSTRUCTIONS, ]) { - if (updated.includes(previous.trim())) { - updated = updated.replace(previous.trim(), WINDOWS_NODE_TRANSPORT_INSTRUCTIONS.trim()); - } + updated = replaceGeneratedSection(updated, previous, WINDOWS_NODE_TRANSPORT_INSTRUCTIONS); } + updated = replaceGeneratedSection( + updated, + WINDOWS_NODE_OFF_MEMORY_INSTRUCTIONS, + WINDOWS_NODE_MEMORY_INSTRUCTIONS, + ); const missing: string[] = []; if (!updated.includes("## Pre-declaring File System Access")) { missing.push(WINDOWS_NODE_ACCESS_SECTION.trim()); @@ -262,11 +430,46 @@ export function updateWindowsNodeInstructions(content: string, legacySection: st if (!updated.includes("## Windows Node command transport")) { missing.push(WINDOWS_NODE_TRANSPORT_INSTRUCTIONS.trim()); } + if (!updated.includes("## MXC filesystem and executable recovery")) { + missing.push(WINDOWS_NODE_MXC_FILESYSTEM_INSTRUCTIONS.trim()); + } if (!updated.includes("## PowerShell command quoting")) { missing.push(WINDOWS_NODE_POWERSHELL_QUOTING_INSTRUCTIONS.trim()); } if (!updated.includes("## PowerShell in MXC scratch")) { missing.push(WINDOWS_NODE_POWERSHELL_SCRATCH_INSTRUCTIONS.trim()); } - return missing.length ? `${updated.trimEnd()}\n\n${missing.join("\n\n")}\n` : updated; + if (!updated.includes("## PowerShell filesystem operations in MXC")) { + missing.push(WINDOWS_NODE_MXC_POWERSHELL_OPERATIONS_INSTRUCTIONS.trim()); + } + if (missing.length) { + const lineEnding = updated.includes("\r\n") ? "\r\n" : "\n"; + const additions = missing + .map((section) => section.replace(/\n/g, lineEnding)) + .join(`${lineEnding}${lineEnding}`); + updated = `${updated.trimEnd()}${lineEnding}${lineEnding}${additions}${lineEnding}`; + } + if (!mxcEnabled) { + for (const section of [ + WINDOWS_NODE_ACCESS_SECTION, + WINDOWS_NODE_PERMISSION_DENIED_INSTRUCTIONS, + WINDOWS_NODE_GIT_INSTRUCTIONS, + WINDOWS_NODE_MXC_FILESYSTEM_INSTRUCTIONS, + WINDOWS_NODE_POWERSHELL_SCRATCH_INSTRUCTIONS, + WINDOWS_NODE_MXC_POWERSHELL_OPERATIONS_INSTRUCTIONS, + ]) { + updated = replaceGeneratedSection(updated, section, ""); + } + updated = replaceGeneratedSection( + updated, + WINDOWS_NODE_MEMORY_INSTRUCTIONS, + WINDOWS_NODE_OFF_MEMORY_INSTRUCTIONS, + ); + updated = replaceGeneratedSection( + updated, + WINDOWS_NODE_TRANSPORT_INSTRUCTIONS, + WINDOWS_NODE_OFF_TRANSPORT_INSTRUCTIONS, + ); + } + return updated; } diff --git a/desktop/src/windows-node-mxc-live-mode.test.ts b/desktop/src/windows-node-mxc-live-mode.test.ts index 2d4e806..895f60d 100644 --- a/desktop/src/windows-node-mxc-live-mode.test.ts +++ b/desktop/src/windows-node-mxc-live-mode.test.ts @@ -1,6 +1,25 @@ +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { runInNewContext } from "node:vm"; +import ts from "typescript"; import { describe, expect, it, vi } from "vitest"; import { applyLiveSandboxMode, type LiveSandboxModeHooks } from "./windows-node-mxc-live-mode"; +const mainSource = readFileSync(resolve(process.cwd(), "src", "main.ts"), "utf8"); +const transitionStart = mainSource.indexOf("async function changeWindowsNodeMxcMode("); +const transitionEnd = mainSource.indexOf( + "async function applyRunningWindowsNodeMxcFolders(", + transitionStart, +); +if (transitionStart < 0 || transitionEnd < 0) { + throw new Error("Cannot locate the live sandbox mode transition"); +} +const transitionJs = ts.transpileModule( + `${mainSource.slice(transitionStart, transitionEnd)} + globalThis.testChangeWindowsNodeMxcMode = changeWindowsNodeMxcMode;`, + { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }, +).outputText; + function hooks() { const calls: string[] = []; const step = (name: string) => @@ -68,4 +87,157 @@ describe("live sandbox mode transaction", () => { cause: recoveryError, }); }); + + function modeReleaseHarness(previousMode: "off" | "full") { + const events: string[] = []; + const generation = "gateway-generation"; + const proof = { + gatewayGeneration: generation, + nodeId: "node", + secretBase64: "secret", + readinessTransitionId: "transition", + policyFingerprint: "policy", + }; + const hostStatus = { + processRunning: true, + processId: 321, + gatewayGeneration: generation, + requestedStrength: previousMode as "off" | "full", + policyFingerprint: proof.policyFingerprint, + }; + const rollback = vi.fn(() => events.push("instructions:rollback")); + const synchronize = vi.fn((enabled: boolean) => { + events.push(`instructions:${enabled}`); + return { updatedFiles: [], rollback }; + }); + const release = vi.fn(() => events.push("ingress:release")); + let captured: LiveSandboxModeHooks | undefined; + const context = { + testChangeWindowsNodeMxcMode: undefined as + | ((params: { enabled: boolean }) => Promise) + | undefined, + windowsNodeMxcUnsupportedWindows: null, + getWindowsNodeMxcSelection: () => ({ requestedMode: previousMode }), + getWindowsNodeMxcRequestedMode: () => previousMode, + isApplicationServiceReady: () => true, + gwClient: { connected: true, connectionGeneration: 7 }, + gatewayProcess: { pid: 123 }, + gatewayGenerationId: generation, + gatewayHttpReadyGeneration: generation, + gatewaySpawnedByUs: true, + isManagedGatewayProcessAlive: () => true, + bundledWindowsNodeGeneration: 4, + bundledWindowsNodeHost: { status: () => hostStatus }, + windowsNodeMxcApprovalProofContext: proof, + settingsStore: { get: () => ({}) }, + migrateWeixinRemoteApprovalConfiguration: () => ({}), + agentRosterChangeInProgress: false, + windowsNodeMxcLifecycleState: "idle", + windowsNodeMxcActivationInProgress: true, + beginWindowsNodeMxcLifecycleOperation: vi.fn(), + endWindowsNodeMxcLifecycleOperation: vi.fn(), + notifyRendererApplicationReady: vi.fn(), + windowsNodeMxcLifecycleOperations: { + run: async ( + _descriptor: unknown, + operation: () => Promise, + hooks: { beforeStart: () => void; afterSettled: () => void }, + ) => { + hooks.beforeStart(); + try { + return await operation(); + } finally { + hooks.afterSettled(); + } + }, + }, + applyLiveSandboxMode: async (hooks: LiveSandboxModeHooks) => { + captured = hooks; + return null; + }, + synchronizeWindowsNodeInstructionsForMode: synchronize, + releaseWindowsNodeMxcIngress: release, + setWindowsNodeMxcLifecycleState: (phase: string) => events.push(`phase:${phase}`), + }; + runInNewContext(transitionJs, context); + return { + context, + events, + hostStatus, + synchronize, + release, + rollback, + async capture(enabled: boolean) { + await context.testChangeWindowsNodeMxcMode!({ enabled }); + if (!captured) throw new Error("Mode transition hooks were not captured"); + hostStatus.requestedStrength = enabled ? "full" : "off"; + return captured; + }, + }; + } + + describe("live sandbox mode guidance", () => { + it.each([ + { previous: "off" as const, enabled: true }, + { previous: "full" as const, enabled: false }, + ])("synchronizes guidance before reopening ingress when enabled=$enabled", async (params) => { + const fixture = modeReleaseHarness(params.previous); + const transition = await fixture.capture(params.enabled); + await transition.release(null); + + expect(fixture.events).toEqual([ + `instructions:${params.enabled}`, + "ingress:release", + `phase:${params.enabled ? "active" : "idle"}`, + ]); + expect(fixture.synchronize).toHaveBeenCalledExactlyOnceWith(params.enabled); + expect(fixture.rollback).not.toHaveBeenCalled(); + }); + + it("does not reopen ingress if synchronizing instructions fails", async () => { + const fixture = modeReleaseHarness("full"); + const transition = await fixture.capture(false); + fixture.synchronize.mockImplementationOnce(() => { + throw new Error("SOUL update failed"); + }); + await expect(transition.release(null)).rejects.toThrow("SOUL update failed"); + expect(fixture.release).not.toHaveBeenCalled(); + }); + + it("rolls instructions back if reopening ingress fails", async () => { + const fixture = modeReleaseHarness("off"); + const transition = await fixture.capture(true); + fixture.release.mockImplementationOnce(() => { + throw new Error("ingress failed"); + }); + await expect(transition.release(null)).rejects.toThrow("ingress failed"); + expect(fixture.rollback).toHaveBeenCalledOnce(); + }); + + it("surfaces both ingress and instruction rollback failures", async () => { + const fixture = modeReleaseHarness("off"); + const transition = await fixture.capture(true); + const ingressError = new Error("ingress failed"); + const rollbackError = new Error("rollback failed"); + fixture.release.mockImplementationOnce(() => { + throw ingressError; + }); + fixture.rollback.mockImplementationOnce(() => { + throw rollbackError; + }); + await expect(transition.release(null)).rejects.toMatchObject({ + errors: [ingressError, rollbackError], + cause: rollbackError, + }); + }); + + it("rejects a mode change while an agent roster change is in progress", async () => { + const fixture = modeReleaseHarness("off"); + fixture.context.agentRosterChangeInProgress = true; + await expect(fixture.capture(true)).rejects.toThrow( + "Wait for the current agent roster change to finish", + ); + expect(fixture.synchronize).not.toHaveBeenCalled(); + }); + }); }); diff --git a/desktop/src/windows-node-mxc-powershell-scope.test.ts b/desktop/src/windows-node-mxc-powershell-scope.test.ts index 280d026..f37cb34 100644 --- a/desktop/src/windows-node-mxc-powershell-scope.test.ts +++ b/desktop/src/windows-node-mxc-powershell-scope.test.ts @@ -6,6 +6,7 @@ import { POWERSHELL_FILESYSTEM_INITIALIZER, validatePowerShellFilesystemInitialization, } from "./windows-node-mxc-powershell-scope"; +import { WINDOWS_NODE_MXC_POWERSHELL_OPERATIONS_INSTRUCTIONS } from "./windows-node-command-instructions"; import { normalizeWindowsNodeMxcGatewayApproval } from "./windows-node-mxc"; import { normalizeWeixinRemoteApprovalOwner, @@ -38,6 +39,23 @@ function preview(payload: string) { } describe("exact contained PowerShell prepared initialization", () => { + it("initializes the exact single-operation example in agent guidance", () => { + const example = WINDOWS_NODE_MXC_POWERSHELL_OPERATIONS_INSTRUCTIONS.match( + /```\nREM \[declare-access\]rw:(.+?)\[\/declare-access\]\n(.+)\n```/, + ); + if (!example) throw new Error("Missing declared PowerShell guidance example"); + const exampleAccess = [{ access: "rw" as const, path: example[1] }]; + const argv = [cmd, "/d", "/s", "/c", example[2]]; + const initialization = createPowerShellFilesystemInitialization(argv, cmd, exampleAccess); + + expect(createPowerShellFilesystemInitialization(argv, cmd, [])).toBeNull(); + expect(initialization?.form).toBe("cmd"); + expect(initialization?.originalArgv).toEqual(argv); + expect(initialization?.finalArgv.at(-1)).toContain( + `${POWERSHELL_FILESYSTEM_INITIALIZER}Remove-Item -LiteralPath 'C:\\work\\old.txt'`, + ); + }); + it.each([false, true])( "retains original literal bytes and independently regenerates form nested=%s", (nested) => { diff --git a/docs/experimental-windows-node-mxc.md b/docs/experimental-windows-node-mxc.md index 6a91223..78c6860 100644 --- a/docs/experimental-windows-node-mxc.md +++ b/docs/experimental-windows-node-mxc.md @@ -90,13 +90,43 @@ enforce those grants. If a conversation contains a stale declaration, its contents remain bound to command consent but are not checked as MXC folder paths and do not restrict host execution. -Generated agent guidance also covers permission-denied recovery: when contained -`exec` fails with a filesystem permission error, the agent should use the +MicroClaw seeds managed agents' `SOUL.md` files according to the sandbox mode +at startup and when an agent is added. A successful live mode change also +updates those files before reopening ingress. Full mode includes the generated +MXC guidance; Off mode removes recognized, unmodified MXC sections while keeping +mode-independent guidance. User-customized sections are preserved and may +still mention MXC in Off mode. The Gateway refreshes bootstrap files for +subsequent turns when it injects them; an in-progress turn and existing +conversation history are not rewritten. + +The Full-mode guidance covers permission-denied recovery: when contained `exec` +fails with a filesystem permission error, the agent should use the reported path to request the smallest necessary directory with `[declare-access]` and fresh consent. It must check for partial effects before retrying, ask when the path is unclear, and never broaden grants repeatedly or bypass MXC. This is -agent guidance, not automatic command rewriting or permission granting; existing -workspaces receive the new section on startup without replacing custom guidance. +agent guidance, not automatic command rewriting or permission granting. + +For ordinary file discovery, the generated guidance prefers available +Gateway-native tools such as `ls` and `read` when their host-side boundary is +acceptable. Those tools run outside MXC; they are not a way to bypass a denied +operation or a request for containment. For contained commands it recommends an +approved `workdir` instead of an absolute CMD `cd`, without claiming that this +fixes other volume-root metadata failures. For missing executables, it suggests +finding the actual installation directory with Gateway `ls` where permitted, +then requesting only that existing directory read-only for a contained command. +An inaccessible listing or an absent sandboxed `where` result does not prove a +program is uninstalled. + +Declarations must name existing directories: to create a new destination, the +guidance selects an appropriately scoped existing parent rather than the missing +child, and checks both declarations and the working directory after +`cwd-not-found`. For PowerShell `Remove-Item`, `Move-Item`, and `Rename-Item`, +it prefers separate literal-path operations where semantics permit, so eligible +commands can use the existing scoped initialization. The initializer requires +explicit RW declarations covering each target even when its directory is +already approved; declaring it does not itself grant access. Complex scripts +that need initialization must include it in the same approved PowerShell +invocation; a separate invocation does not retain the initialized drive. **Ask when needed** uses the upstream Windows Node command allowlist and asks for commands that are not already permitted. **Allow always** disables those