Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ export type HardBlockedCategory =
| 'windows-secure-erase'
// Windows CMD/PowerShell delete commands. CLI-driven deletes on Windows
// skip the Recycle Bin entirely and are irrecoverable. With the Windows
// mavis-trash.js script now available, the rm-rewrite pipeline can
// mavis-trash.cjs script now available, the rm-rewrite pipeline can
// intercept these — but until that rewrite path is wired for Windows
// delete commands (del/rd/Remove-Item), the safest policy is HARD deny.
| 'windows-delete'
Expand Down Expand Up @@ -530,7 +530,7 @@ const HARD_BLOCKED_BASH_PATTERNS: ReadonlyArray<{

// ---- windows-delete: CMD/PowerShell delete commands. CLI-driven Windows
// deletes do not move to Recycle Bin and are irrecoverable. The Windows
// mavis-trash.js script provides Recycle Bin support, but rm-rewrite for
// mavis-trash.cjs script provides Recycle Bin support, but rm-rewrite for
// Windows delete commands (del/rd/Remove-Item) is not yet wired, so HARD
// deny until that pipeline is extended.
{
Expand Down
30 changes: 27 additions & 3 deletions packages/agent-modules/skills/src/directory-watcher.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { watch, type FSWatcher } from 'node:fs';
import { realpathSync, watch, type FSWatcher } from 'node:fs';
import path from 'node:path';

interface DirectoryIdentity {
Expand All @@ -22,17 +22,41 @@ interface SharedWatcher {
// on macOS; evicting one registry must only release its own subscriptions.
const sharedWatchers = new Map<string, SharedWatcher>();

/**
* The path the watcher is bound to.
*
* Windows reports a changed file under its long name, and libuv compares that
* name against the directory string the watch was given. A directory reached
* through its 8.3 short alias — which is what a temp directory under a
* short-named home directory spells — therefore fails libuv's own
* `!_wcsnicmp(filename, dir, dirlen)` assertion, and that assertion takes the
* process down rather than raising an error.
*
* `realpathSync.native` resolves the alias to the long path; the JavaScript
* implementation of `realpathSync` does not, so the native one is the one that
* matters here. A directory that cannot be resolved (it does not exist yet)
* falls back to the resolved path it was given.
*/
function watchableDirectory(targetPath: string): string {
try {
return realpathSync.native(targetPath);
} catch {
return path.resolve(targetPath);
}
}

export function subscribeToSkillDirectory(
target: DirectoryIdentity,
subscriber: Subscriber,
): { close(): void } {
const watchPath = watchableDirectory(target.targetPath);
// Include filesystem identity so replacing a directory at the same path
// never reuses a watcher still bound to the removed directory.
const key = JSON.stringify([path.resolve(target.targetPath), target.dev, target.ino]);
const key = JSON.stringify([watchPath, target.dev, target.ino]);
let shared = sharedWatchers.get(key);
if (!shared) {
const subscribers = new Set<Subscriber>();
const watcher = watch(target.targetPath, { persistent: false }, () => {
const watcher = watch(watchPath, { persistent: false }, () => {
for (const current of [...subscribers]) current.onChange();
});
shared = { watcher, subscribers };
Expand Down
97 changes: 97 additions & 0 deletions packages/agent-modules/skills/test/directory-watcher.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { describe, expect, it } from "vitest";
import { execFileSync } from "node:child_process";
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";

const repoRoot = fileURLToPath(new URL("../../../../", import.meta.url));
const watcherModule = path.join(
repoRoot,
"packages/agent-modules/skills/src/directory-watcher.ts",
);

/**
* The child subscribes to the directory and writes into it.
*
* The watch and the write have to disagree about how the path is spelled,
* because that is the whole defect: on Windows the filesystem reports a
* changed file under its long name, and libuv compares that name against the
* directory string it was given. Watching the 8.3 short alias and writing
* through the long path makes the two names differ, and libuv's own
* assertion (`!_wcsnicmp(filename, dir, dirlen)`) aborts the process.
*
* The child runs in its own process on purpose: that assertion is not a
* catchable error, it takes the whole process down. Isolating it here means
* a regression is a failed assertion instead of a dead test worker.
*/
const CHILD = `
import { execFileSync } from "node:child_process";
import { writeFileSync } from "node:fs";
import { join } from "node:path";

const { subscribeToSkillDirectory } = await import(process.argv[2]);

const directory = process.argv[3];
// Ask Windows for the 8.3 alias of the directory. The path is passed to cmd
// without quotes: an embedded quote is mangled by the way a Windows child
// process receives its command line, and the alias is then spelled wrong.
let watchPath = directory;
if (process.platform === "win32" && !directory.includes(" ")) {
try {
watchPath = execFileSync(
"cmd.exe",
["/d", "/c", \`for %I in (\${directory}) do @echo %~sI\`],
{ encoding: "utf8" },
).trim();
} catch {
watchPath = directory;
}
}

let changed = false;
const subscription = subscribeToSkillDirectory(
{ targetPath: watchPath, dev: 0, ino: 0 },
{ onChange: () => { changed = true; }, onError: () => {} },
);
writeFileSync(join(directory, "probe.md"), "probe");
const deadline = Date.now() + 8000;
while (!changed && Date.now() < deadline) {
await new Promise((resolve) => setTimeout(resolve, 25));
}
subscription.close();
process.stdout.write(JSON.stringify({ watchPath, directory, changed }));
process.exit(changed ? 0 : 3);
`;

describe("the skill directory watcher", () => {
it("reports a change when the watch and the write spell the path differently", () => {
const scratch = mkdtempSync(path.join(tmpdir(), "skills-watcher-"));
const childPath = path.join(scratch, "child.mts");
writeFileSync(childPath, CHILD, "utf8");

let stdout = "";
let status: number | null = null;
let stderr = "";
try {
const result = execFileSync(
process.execPath,
["--import", "tsx", childPath, `file:///${watcherModule.replace(/\\/gu, "/")}`, scratch],
{ cwd: repoRoot, encoding: "utf8", timeout: 40_000 },
);
stdout = result;
status = 0;
} catch (error) {
const failure = error as { status?: number; stdout?: string; stderr?: string };
status = failure.status ?? null;
stdout = failure.stdout ?? "";
stderr = failure.stderr ?? "";
}

expect(
{ status, stdout, stderr },
`the child must survive and report the change; stderr was:\n${stderr}`,
).toMatchObject({ status: 0 });
expect(JSON.parse(stdout).changed).toBe(true);
});
});
14 changes: 13 additions & 1 deletion packages/agent-tools/src/desktop/host-trash-executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,13 +147,25 @@ export async function executeLocalHostTrashIfRequested(input: {
}
}

/**
* The file names the Windows trash shim is known by.
*
* The shim is a CommonJS script, and `.cjs` is what says so: it is
* CommonJS whatever the nearest ancestor `package.json` says, while a `.js`
* shim follows that ancestor and can be parsed as ESM. The previous `.js`
* name is still accepted, because a runtime pointed at it is a stale
* configuration rather than a reason to refuse the operation here — whether
* the script actually runs is decided by the probe, not by its name.
*/
const WINDOWS_TRASH_SCRIPT_NAMES = new Set(['mavis-trash.cjs', 'mavis-trash.js']);

function isAvailableWindowsTrashRuntime(
runtime: LocalHostTrashRuntime,
): runtime is LocalHostTrashRuntime & { readonly scriptPath: string } {
return (
typeof runtime.scriptPath === 'string' &&
path.isAbsolute(runtime.scriptPath) &&
path.basename(runtime.scriptPath).toLowerCase() === 'mavis-trash.js'
WINDOWS_TRASH_SCRIPT_NAMES.has(path.basename(runtime.scriptPath).toLowerCase())
);
}

Expand Down
44 changes: 39 additions & 5 deletions packages/agent-tools/test/desktop/local-bash-output.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { LocalBashTool } from '../../src/desktop/local-pi-tools.js';
import { resolveLocalBashShell } from '../../src/desktop/local-bash-contract.js';
import { DESKTOP_BASH_MAX_BYTES } from '../../src/desktop/output-limit.js';
import { readPluginHookCompatibleToolResponse } from '../../src/plugin-hooks/vendor-tool-response.js';
import type { LocalRuntimeToolContext } from '../../src/desktop/types.js';
Expand All @@ -19,6 +20,37 @@ const SESSION_CTX = {
turnId: 'turn-test',
} satisfies LocalRuntimeToolContext;

/**
* The shell the tool will actually run.
*
* On Windows the runtime prefers PowerShell, and PowerShell reads a quoted
* path as a string expression rather than as a program to run — it needs the
* call operator — and it has no `printf`. A command written for `sh` is a
* ParserError there, so the commands below are spelled for the shell that
* will run them.
*/
const shell = resolveLocalBashShell();
const isPosixShell = shell === 'bash' || shell === 'sh';

/** A command that runs the given script with this process's Node. */
function nodeCommand(script: string): string {
const executable = JSON.stringify(process.execPath);
const source = JSON.stringify(script);
// PowerShell reports the native exit code in $LASTEXITCODE and exits with
// its own status unless it is told otherwise, so the code has to be carried
// over explicitly for a failing command to stay a failing command.
return isPosixShell
? `${executable} -e ${source}`
: `& ${executable} -e ${source}; exit $LASTEXITCODE`;
}

/** A command that writes the given text to stdout and to stderr, exactly. */
function splitStreamCommand(stdout: string, stderr: string): string {
return isPosixShell
? `printf '${stdout}'; printf '${stderr}' >&2`
: `[Console]::Out.Write('${stdout}');[Console]::Error.Write('${stderr}')`;
}

describe('LocalBashTool — foreground output truncation', () => {
let workspace: string;

Expand All @@ -32,7 +64,7 @@ describe('LocalBashTool — foreground output truncation', () => {
it('preserves exact stdout and stderr for Compatible PostToolUse', async () => {
const tool = new LocalBashTool(workspace, undefined, { mode: 'off' });
const result = await tool.execute(SESSION_CTX, {
command: "printf 'from-stdout'; printf 'from-stderr' >&2",
command: splitStreamCommand('from-stdout', 'from-stderr'),
});

expect(readPluginHookCompatibleToolResponse(result)).toEqual({
Expand All @@ -44,7 +76,9 @@ describe('LocalBashTool — foreground output truncation', () => {

it('short output is returned verbatim, not truncated', async () => {
const tool = new LocalBashTool(workspace, undefined, { mode: 'off' });
const result = await tool.execute(SESSION_CTX, { command: 'printf "a\\nb\\nc\\n"' });
const result = await tool.execute(SESSION_CTX, {
command: isPosixShell ? 'printf "a\\nb\\nc\\n"' : '[Console]::Out.Write("a`nb`nc`n")',
});
expect(result.tool_name).toBe('bash');
expect(result.isError).toBeFalsy();
expect(result.text).toContain('a');
Expand All @@ -54,7 +88,7 @@ describe('LocalBashTool — foreground output truncation', () => {
it('caps 24-50 KiB foreground output with head and tail and persists the complete output', async () => {
const tool = new LocalBashTool(workspace, undefined, { mode: 'off' });
const script = `for(let i=0;i<400;i++) console.log('row-'+i+'-'+'x'.repeat(90))`;
const command = `${JSON.stringify(process.execPath)} -e ${JSON.stringify(script)}`;
const command = nodeCommand(script);
const result = await tool.execute(SESSION_CTX, { command });

expect(Buffer.byteLength(result.text, 'utf8')).toBeLessThanOrEqual(
Expand Down Expand Up @@ -131,7 +165,7 @@ describe('LocalBashTool — foreground output truncation', () => {
const tool = new LocalBashTool(workspace, undefined, { mode: 'off' });
// Let pending stderr writes drain before exiting with the intended error code.
const script = `for(let i=0;i<400;i++) console.error('error-row-'+i+'-'+'e'.repeat(90)); process.exitCode = 7`;
const command = `${JSON.stringify(process.execPath)} -e ${JSON.stringify(script)}`;
const command = nodeCommand(script);
const result = await tool.execute(SESSION_CTX, { command });

expect(result.isError).toBe(true);
Expand Down Expand Up @@ -161,7 +195,7 @@ describe('LocalBashTool — foreground output truncation', () => {
it('output beyond 2000 lines preserves head and tail with a complete output file', async () => {
const tool = new LocalBashTool(workspace, undefined, { mode: 'off' });
const script = `for(let i=0;i<3000;i++) console.log('spill-row-'+i+'-'+'z'.repeat(50))`;
const command = `${JSON.stringify(process.execPath)} -e ${JSON.stringify(script)}`;
const command = nodeCommand(script);
const result = await tool.execute(SESSION_CTX, { command });

const lower = result.text.toLowerCase();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { watch, type FSWatcher } from 'node:fs';
import { realpathSync, watch, type FSWatcher } from 'node:fs';
import { mkdir } from 'node:fs/promises';

import {
Expand Down Expand Up @@ -58,7 +58,22 @@ export class LocalPluginDirectoryWatcher implements LocalPluginDirectoryWatcherP
}

protected createWatcher(root: string, onChange: () => void): FSWatcher {
return watch(root, { persistent: false, recursive: true }, onChange);
// Windows reports a changed file under its long name, and libuv compares
// that name against the directory string the watch was given. A directory
// reached through its 8.3 short alias — which is how the plugin directory
// under a short-named home directory spells itself — therefore fails
// libuv's own `!_wcsnicmp(filename, dir, dirlen)` assertion, and that
// assertion takes the process down rather than raising an error.
//
// `realpathSync.native` resolves the alias to the long path; the
// JavaScript implementation of `realpathSync` does not.
let watchPath = root;
try {
watchPath = realpathSync.native(root);
} catch {
watchPath = root;
}
return watch(watchPath, { persistent: false, recursive: true }, onChange);
}

async whenIdle(): Promise<void> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,11 @@ describe("srt-macos backend", () => {
// an empty dir under sandboxTempDir so git init/clone skip hook-template
// copies (an empty env value no longer skips on git >= 2.53).
env: {
GIT_TEMPLATE_DIR: "/tmp/session-1/git-templates-empty",
// The backend joins the template dir onto the sandbox temp dir, so the
// path carries the host's separator. A POSIX-shaped literal here never
// matched on Windows, where the directory is
// `\tmp\session-1\git-templates-empty`.
GIT_TEMPLATE_DIR: join("/tmp/session-1", "git-templates-empty"),
...baseEnv,
MAVIS_TRASH_FORCE_MV: "1",
},
Expand Down
6 changes: 3 additions & 3 deletions packages/local-runtime/src/infra/ensure-trash-script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
* fell back to `/bin/rm` — hard-deleting the user's files.
*
* - macOS / Linux: seeds a POSIX bash script at `mavis-trash` (0o755).
* - Windows: seeds a Node.js script at `mavis-trash.js` plus a `.cmd`
* - Windows: seeds a Node.js script at `mavis-trash.cjs` plus a `.cmd`
* launcher `mavis-trash.cmd`, so the permission pipeline can invoke
* `mavis-trash <paths>` uniformly across platforms.
*
Expand All @@ -36,7 +36,7 @@ export function ensureTrashScript(
const isWin = platform === 'win32';

if (isWin) {
seedFileIfChanged(path.join(binDir, 'mavis-trash.js'), TRASH_SCRIPT_WIN_CONTENT);
seedFileIfChanged(path.join(binDir, 'mavis-trash.cjs'), TRASH_SCRIPT_WIN_CONTENT);
seedFileIfChanged(path.join(binDir, 'mavis-trash.cmd'), TRASH_CMD_LAUNCHER_CONTENT);
} else {
seedFileIfChanged(path.join(binDir, 'mavis-trash'), TRASH_SCRIPT_CONTENT, 0o755);
Expand Down Expand Up @@ -153,7 +153,7 @@ export function inspectTrashRuntime(
}
}
if (platform !== 'win32') return { available: true };
const scriptPath = path.join(dataDir, 'bin', 'mavis-trash.js');
const scriptPath = path.join(dataDir, 'bin', 'mavis-trash.cjs');
const launcherPath = path.join(dataDir, 'bin', 'mavis-trash.cmd');
const cacheKey = `${platform}:${dataDir}`;
let phase: TrashRuntimeDiagnostics['phase'] = 'read-script';
Expand Down
15 changes: 11 additions & 4 deletions packages/local-runtime/src/infra/trash-script-win.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
/**
* mavis-trash.js — Node.js script that moves files to Windows Recycle Bin.
* mavis-trash.cjs — Node.js script that moves files to Windows Recycle Bin.
*
* Seeded into `<dataDir>/bin/mavis-trash.js` on daemon startup (Windows only).
* Seeded into `<dataDir>/bin/mavis-trash.cjs` on daemon startup (Windows only).
* Companion to the POSIX bash `mavis-trash` script (macOS/Linux).
*
* The extension is not a detail. The script is CommonJS, and Node reads the
* module type of a `.js` file from the nearest ancestor `package.json`: an
* ancestor that says `"type": "module"` — a user's home directory can easily
* hold one — makes Node parse this script as ESM, where `require` is not
* defined, and the script never runs. `.cjs` says CommonJS whatever the
* ancestor says.
*
* Uses PowerShell's Microsoft.VisualBasic.FileIO API to send files/directories
* to the Recycle Bin, which is the Windows equivalent of macOS Finder Trash.
*
Expand All @@ -14,7 +21,7 @@
/* eslint-disable no-useless-escape */

/**
* The Node.js script content. Runs standalone via `node mavis-trash.js [flags] file1 file2 ...`.
* The Node.js script content. Runs standalone via `node mavis-trash.cjs [flags] file1 file2 ...`.
*
* Matches the bash script's interface:
* - Silently strips rm-style flags (-r, -f, -rf, --recursive, --force, -R, --)
Expand Down Expand Up @@ -626,7 +633,7 @@ export function buildTrashCmdLauncherContent(runtimeExecutable: string = process
const escapedExecutable = runtimeExecutable.replaceAll('%', '%%').replaceAll('"', '""');
return `@echo off
set "ELECTRON_RUN_AS_NODE=1"
"${escapedExecutable}" "%~dp0mavis-trash.js" %*
"${escapedExecutable}" "%~dp0mavis-trash.cjs" %*
`;
}

Expand Down
Loading
Loading