refactor: remove Waggle Room captured tasks for external coding agents
Waggle Room is not part of the community edition (decision Q2, ADR-0002). Its headless runs of Claude Code, Codex, Hermes and OpenClaw needed the packaged collaboration CLI from the removed @waggle/hive-mind-cli, so POST /api/tools/run answered 503 collaboration_runtime_missing. - Remove POST /api/tools/run (routes/external-tool-runs.ts) with its Room fan-out, WaggleDance publishing, OpenClaw provisioning and the memory write-back of run results. - Remove runExternalTool (agent/external-tool-runner.ts) and resolveWaggleRuntime; the taskkill path helper moves into the process tracker, its only remaining user. - Launcher: drop the hidden "Run task" composer, the Room hand-off and adapter.runExternalToolTask. Detect, launch, watch and stop stay. - Drop the `room` flag from the memory feature map: it only gated the Launcher task button. - The viewer policy no longer reads participants[].workspaceIds, a body shape only /api/tools/run accepted.
This commit is contained in:
@@ -1,9 +1,5 @@
|
||||
/**
|
||||
* LauncherApp — detect, launch, watch and stop external AI tools.
|
||||
*
|
||||
* Waggle Room tasks are hidden in v1 by the memory feature map (ADR-0002).
|
||||
* Most suites switch them on to keep the hidden code covered; the "v1 memory
|
||||
* features" suite checks the default.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen, waitFor, cleanup, fireEvent, within } from '@testing-library/react';
|
||||
@@ -14,15 +10,11 @@ const mocks = vi.hoisted(() => ({
|
||||
getToolProcesses: vi.fn(),
|
||||
launchTool: vi.fn(),
|
||||
killTool: vi.fn(),
|
||||
runExternalToolTask: vi.fn(),
|
||||
streamToolOutput: vi.fn(() => () => {}),
|
||||
},
|
||||
}));
|
||||
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
|
||||
|
||||
const features = vi.hoisted(() => ({ enabled: true }));
|
||||
vi.mock('@/lib/memory-features', () => ({ hasMemoryFeature: () => features.enabled }));
|
||||
|
||||
import LauncherApp, { resetLauncherRouteCache } from './LauncherApp';
|
||||
|
||||
const detectionResp = {
|
||||
@@ -40,16 +32,11 @@ const detectionResp = {
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
features.enabled = true;
|
||||
resetLauncherRouteCache();
|
||||
mocks.adapter.detectTools.mockResolvedValue(detectionResp);
|
||||
mocks.adapter.getToolProcesses.mockResolvedValue({ processes: [] });
|
||||
mocks.adapter.launchTool.mockResolvedValue({ ok: true, pid: 123 });
|
||||
mocks.adapter.killTool.mockResolvedValue({ ok: true, pid: 123, reason: 'SIGTERM' });
|
||||
mocks.adapter.runExternalToolTask.mockResolvedValue({
|
||||
roomId: 'room-1',
|
||||
runs: [{ runId: 'run-1', workspaceId: 'ws-1', status: 'queued', statusUrl: '/api/agent-runs/run-1' }],
|
||||
});
|
||||
});
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
@@ -91,181 +78,36 @@ describe('LauncherApp · live output (#4)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('LauncherApp · captured tasks', () => {
|
||||
it('fans Codex and Hermes into two workspaces and opens their shared Room', async () => {
|
||||
const onOpenRoom = vi.fn();
|
||||
mocks.adapter.detectTools.mockResolvedValue({
|
||||
platform: 'darwin',
|
||||
detectedAt: '2026-07-11T00:00:00.000Z',
|
||||
tools: [
|
||||
{
|
||||
id: 'codex',
|
||||
displayName: 'Codex CLI',
|
||||
installed: true,
|
||||
installedPath: '/usr/local/bin/codex',
|
||||
version: '0.144.1',
|
||||
capabilities: {
|
||||
interactiveLaunch: true,
|
||||
headlessTask: true,
|
||||
structuredProgress: true,
|
||||
resumable: true,
|
||||
liveWaggleDance: false,
|
||||
},
|
||||
permissionModes: ['read-only', 'workspace-write', 'native'],
|
||||
},
|
||||
{
|
||||
id: 'hermes',
|
||||
displayName: 'Hermes',
|
||||
installed: true,
|
||||
installedPath: '/usr/local/bin/hermes',
|
||||
version: '1.0.0',
|
||||
capabilities: {
|
||||
interactiveLaunch: true,
|
||||
headlessTask: true,
|
||||
structuredProgress: true,
|
||||
resumable: true,
|
||||
liveWaggleDance: true,
|
||||
},
|
||||
permissionModes: ['native'],
|
||||
},
|
||||
{
|
||||
id: 'cursor',
|
||||
displayName: 'Cursor',
|
||||
installed: true,
|
||||
installedPath: '/Applications/Cursor.app',
|
||||
version: '1.0.0',
|
||||
capabilities: {
|
||||
interactiveLaunch: true,
|
||||
headlessTask: false,
|
||||
structuredProgress: false,
|
||||
resumable: false,
|
||||
liveWaggleDance: false,
|
||||
},
|
||||
permissionModes: [],
|
||||
},
|
||||
{
|
||||
id: 'openclaw',
|
||||
displayName: 'OpenClaw',
|
||||
installed: false,
|
||||
installedPath: null,
|
||||
version: null,
|
||||
capabilities: {
|
||||
interactiveLaunch: true,
|
||||
headlessTask: true,
|
||||
structuredProgress: true,
|
||||
resumable: true,
|
||||
liveWaggleDance: true,
|
||||
},
|
||||
permissionModes: ['native'],
|
||||
},
|
||||
],
|
||||
});
|
||||
mocks.adapter.runExternalToolTask.mockResolvedValue({
|
||||
roomId: 'room-multi',
|
||||
runs: [
|
||||
{ runId: 'codex-a', toolId: 'codex', workspaceId: 'ws-a', status: 'queued', statusUrl: '/api/agent-runs/codex-a' },
|
||||
{ runId: 'codex-b', toolId: 'codex', workspaceId: 'ws-b', status: 'queued', statusUrl: '/api/agent-runs/codex-b' },
|
||||
{ runId: 'hermes-a', toolId: 'hermes', workspaceId: 'ws-a', status: 'queued', statusUrl: '/api/agent-runs/hermes-a' },
|
||||
{ runId: 'hermes-b', toolId: 'hermes', workspaceId: 'ws-b', status: 'queued', statusUrl: '/api/agent-runs/hermes-b' },
|
||||
{ runId: 'synthesis', toolId: 'hermes', workspaceId: 'ws-b', status: 'queued', statusUrl: '/api/agent-runs/synthesis' },
|
||||
],
|
||||
});
|
||||
|
||||
render(
|
||||
<LauncherApp
|
||||
activeWorkspaceId="ws-a"
|
||||
workspaces={[
|
||||
{ id: 'ws-a', name: 'Alpha' },
|
||||
{ id: 'ws-b', name: 'Beta' },
|
||||
]}
|
||||
onOpenRoom={onOpenRoom}
|
||||
/>,
|
||||
);
|
||||
|
||||
const codexCard = await screen.findByTestId('launcher-tool-codex');
|
||||
fireEvent.click(within(codexCard).getByRole('button', { name: /run task/i }));
|
||||
expect(screen.getByRole('checkbox', { name: 'Codex CLI' })).toBeChecked();
|
||||
expect(screen.getByRole('checkbox', { name: 'Hermes' })).not.toBeChecked();
|
||||
expect(screen.queryByRole('checkbox', { name: 'Cursor' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('checkbox', { name: 'OpenClaw' })).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'Hermes' }));
|
||||
fireEvent.change(screen.getByRole('combobox', { name: 'Access for Codex CLI' }), {
|
||||
target: { value: 'workspace-write' },
|
||||
});
|
||||
expect(screen.getByRole('combobox', { name: 'Access for Hermes' })).toHaveValue('native');
|
||||
expect(screen.getByRole('checkbox', { name: 'Alpha' })).toBeChecked();
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'Beta' }));
|
||||
fireEvent.change(screen.getByLabelText('Task for Codex CLI'), {
|
||||
target: { value: ' Compare both implementations ' },
|
||||
});
|
||||
fireEvent.click(screen.getByRole('button', { name: /start in room/i }));
|
||||
|
||||
await waitFor(() => expect(mocks.adapter.runExternalToolTask).toHaveBeenCalledWith({
|
||||
participants: [
|
||||
{ toolId: 'codex', access: 'workspace-write' },
|
||||
{ toolId: 'hermes', access: 'native' },
|
||||
],
|
||||
workspaceIds: ['ws-a', 'ws-b'],
|
||||
prompt: 'Compare both implementations',
|
||||
}));
|
||||
expect(screen.getByText('Started 2 agents across 2 workspaces (5 worker runs). Opening Room.')).toBeInTheDocument();
|
||||
expect(onOpenRoom).toHaveBeenCalledWith('room-multi');
|
||||
});
|
||||
|
||||
it('labels a roadmap tool and offers no launch or task actions', async () => {
|
||||
describe('LauncherApp · availability', () => {
|
||||
it('labels a roadmap tool and offers no launch action', async () => {
|
||||
mocks.adapter.detectTools.mockResolvedValue({
|
||||
platform: 'darwin',
|
||||
detectedAt: '2026-07-11T00:00:00.000Z',
|
||||
tools: [{
|
||||
id: 'cursor',
|
||||
displayName: 'Cursor',
|
||||
releaseStatus: 'roadmap',
|
||||
launchable: false,
|
||||
id: 'cursor',
|
||||
displayName: 'Cursor',
|
||||
releaseStatus: 'roadmap',
|
||||
launchable: false,
|
||||
installed: true,
|
||||
installedPath: '/Applications/Cursor.app',
|
||||
version: '1.0.0',
|
||||
capabilities: {
|
||||
interactiveLaunch: true,
|
||||
headlessTask: false,
|
||||
structuredProgress: false,
|
||||
resumable: false,
|
||||
liveWaggleDance: false,
|
||||
},
|
||||
permissionModes: [],
|
||||
}],
|
||||
});
|
||||
|
||||
render(<LauncherApp workspaces={[{ id: 'ws-a', name: 'Alpha' }]} />);
|
||||
render(<LauncherApp />);
|
||||
|
||||
const card = await screen.findByTestId('launcher-tool-cursor');
|
||||
expect(within(card).getByText('Roadmap')).toBeInTheDocument();
|
||||
expect(within(card).getByText(/detection retained for compatibility/i)).toBeInTheDocument();
|
||||
expect(within(card).queryByText('Detect only')).not.toBeInTheDocument();
|
||||
expect(within(card).queryByRole('button', { name: /^launch$/i })).not.toBeInTheDocument();
|
||||
expect(within(card).queryByRole('button', { name: /run task/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('launches Hermes Desktop but excludes it and a broken CLI from captured teams', async () => {
|
||||
it('launches Hermes Desktop and explains why a broken Hermes CLI cannot launch', async () => {
|
||||
mocks.adapter.detectTools.mockResolvedValue({
|
||||
platform: 'win32',
|
||||
detectedAt: '2026-07-17T00:00:00.000Z',
|
||||
tools: [
|
||||
{
|
||||
id: 'codex',
|
||||
displayName: 'Codex CLI',
|
||||
installed: true,
|
||||
installedPath: 'C:\\tools\\codex.exe',
|
||||
version: '0.144.1',
|
||||
launchable: true,
|
||||
capabilities: {
|
||||
interactiveLaunch: true,
|
||||
headlessTask: true,
|
||||
structuredProgress: true,
|
||||
resumable: true,
|
||||
liveWaggleDance: false,
|
||||
},
|
||||
permissionModes: ['read-only', 'workspace-write', 'native'],
|
||||
},
|
||||
{
|
||||
id: 'hermes',
|
||||
displayName: 'Hermes Agent CLI',
|
||||
@@ -274,14 +116,6 @@ describe('LauncherApp · captured tasks', () => {
|
||||
version: null,
|
||||
launchable: false,
|
||||
diagnostic: 'Hermes failed its --version health check.',
|
||||
capabilities: {
|
||||
interactiveLaunch: true,
|
||||
headlessTask: true,
|
||||
structuredProgress: false,
|
||||
resumable: true,
|
||||
liveWaggleDance: false,
|
||||
},
|
||||
permissionModes: ['native'],
|
||||
},
|
||||
{
|
||||
id: 'hermes-desktop',
|
||||
@@ -290,32 +124,39 @@ describe('LauncherApp · captured tasks', () => {
|
||||
installedPath: 'C:\\Users\\test\\AppData\\Local\\hermes\\Hermes.exe',
|
||||
version: null,
|
||||
launchable: true,
|
||||
capabilities: {
|
||||
interactiveLaunch: true,
|
||||
headlessTask: false,
|
||||
structuredProgress: false,
|
||||
resumable: false,
|
||||
liveWaggleDance: false,
|
||||
},
|
||||
permissionModes: [],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
render(<LauncherApp workspaces={[{ id: 'ws-a', name: 'Alpha' }]} />);
|
||||
render(<LauncherApp />);
|
||||
|
||||
const desktopCard = await screen.findByTestId('launcher-tool-hermes-desktop');
|
||||
expect(within(desktopCard).getByRole('button', { name: /^launch$/i })).toBeInTheDocument();
|
||||
expect(within(desktopCard).queryByRole('button', { name: /run task/i })).not.toBeInTheDocument();
|
||||
|
||||
const cliCard = screen.getByTestId('launcher-tool-hermes');
|
||||
expect(within(cliCard).queryByRole('button', { name: /^launch$/i })).not.toBeInTheDocument();
|
||||
expect(within(cliCard).queryByRole('button', { name: /run task/i })).not.toBeInTheDocument();
|
||||
expect(within(cliCard).getByText(/failed its --version health check/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(within(screen.getByTestId('launcher-tool-codex')).getByRole('button', { name: /run task/i }));
|
||||
expect(screen.queryByRole('checkbox', { name: 'Hermes Agent CLI' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('checkbox', { name: 'Hermes Desktop' })).not.toBeInTheDocument();
|
||||
it('offers no captured-task controls: Waggle Room is not part of this edition', async () => {
|
||||
mocks.adapter.detectTools.mockResolvedValue({
|
||||
platform: 'darwin',
|
||||
detectedAt: '2026-07-11T00:00:00.000Z',
|
||||
tools: [{
|
||||
id: 'codex',
|
||||
displayName: 'Codex CLI',
|
||||
installed: true,
|
||||
installedPath: '/usr/local/bin/codex',
|
||||
version: '0.144.1',
|
||||
}],
|
||||
});
|
||||
|
||||
render(<LauncherApp />);
|
||||
|
||||
const card = await screen.findByTestId('launcher-tool-codex');
|
||||
expect(within(card).getByRole('button', { name: /^launch$/i })).toBeInTheDocument();
|
||||
expect(within(card).queryByRole('button', { name: /run task/i })).not.toBeInTheDocument();
|
||||
expect(screen.queryByText(/room/i)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -409,30 +250,3 @@ describe('LauncherApp · launch', () => {
|
||||
expect(screen.getByRole('button', { name: /^launch$/i })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('LauncherApp · v1 memory features (ADR-0002)', () => {
|
||||
it('hides Room tasks; launch stays', async () => {
|
||||
features.enabled = false;
|
||||
mocks.adapter.detectTools.mockResolvedValue({
|
||||
platform: 'darwin',
|
||||
detectedAt: '2026-07-11T00:00:00.000Z',
|
||||
tools: [
|
||||
{
|
||||
id: 'codex',
|
||||
displayName: 'Codex CLI',
|
||||
installed: true,
|
||||
installedPath: '/usr/local/bin/codex',
|
||||
version: '0.144.1',
|
||||
capabilities: { interactiveLaunch: true, headlessTask: true, structuredProgress: true, resumable: true },
|
||||
permissionModes: ['read-only', 'workspace-write', 'native'],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
render(<LauncherApp />);
|
||||
|
||||
expect(await screen.findByText('Codex CLI')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /^launch$/i })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /run task/i })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,13 +14,12 @@
|
||||
import { useState, useEffect, useCallback, useMemo } from 'react';
|
||||
import {
|
||||
Rocket, RefreshCw, CheckCircle2, XCircle, AlertTriangle,
|
||||
Play, Loader2, MessageSquare, Square, Workflow,
|
||||
Play, Loader2, MessageSquare, Square,
|
||||
} from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { adapter } from '@/lib/adapter';
|
||||
import { hasMemoryFeature } from '@/lib/memory-features';
|
||||
import { createSurfaceCache } from '@/lib/surface-cache';
|
||||
import {
|
||||
promptArgsForTool,
|
||||
@@ -29,8 +28,6 @@ import {
|
||||
import { ToolOutputPane } from './launcher/ToolOutputPane';
|
||||
import {
|
||||
BUILTIN_TOOL_MANIFESTS,
|
||||
type ExternalToolAccess,
|
||||
type ToolCapabilities,
|
||||
type ToolReleaseStatus,
|
||||
} from '@waggle/shared';
|
||||
|
||||
@@ -46,8 +43,6 @@ interface DetectedTool {
|
||||
launchable?: boolean;
|
||||
builtin?: boolean;
|
||||
acceptsInlinePrompt?: boolean;
|
||||
capabilities?: ToolCapabilities;
|
||||
permissionModes?: readonly ExternalToolAccess[];
|
||||
installed: boolean;
|
||||
installedPath: string | null;
|
||||
version: string | null;
|
||||
@@ -60,25 +55,15 @@ interface DetectionResult {
|
||||
tools: DetectedTool[];
|
||||
}
|
||||
|
||||
type ToolAction = 'launch' | 'run';
|
||||
|
||||
interface ActionState {
|
||||
toolId: string;
|
||||
action: ToolAction;
|
||||
}
|
||||
|
||||
interface ActionResult {
|
||||
toolId: string;
|
||||
action: ToolAction;
|
||||
ok: boolean;
|
||||
message: string;
|
||||
}
|
||||
|
||||
interface LauncherAppProps {
|
||||
/** Active workspace id — injected into spawned tools as WAGGLE_WORKSPACE_ID. */
|
||||
/** Active workspace: the launched tool starts in its folder. */
|
||||
activeWorkspaceId?: string;
|
||||
workspaces?: Array<{ id: string; name: string; status?: string }>;
|
||||
onOpenRoom?: (roomId: string) => void;
|
||||
}
|
||||
|
||||
/** Keep tool detection visible while the Launcher revalidates on return. */
|
||||
@@ -95,7 +80,7 @@ const toolCanLaunch = (tool: DetectedTool): boolean =>
|
||||
|
||||
const launchUnavailableMessage = (tool: DetectedTool): string =>
|
||||
tool.releaseStatus === 'roadmap'
|
||||
? 'Roadmap integration. Detection retained for compatibility; launch and tasks are deferred.'
|
||||
? 'Roadmap integration. Detection retained for compatibility; launch is deferred.'
|
||||
: tool.installed && tool.diagnostic
|
||||
? 'Launch is blocked for this install. Follow the note above, then refresh.'
|
||||
: 'Detection ready. This adapter is not configured for launch.';
|
||||
@@ -103,38 +88,15 @@ const launchUnavailableMessage = (tool: DetectedTool): string =>
|
||||
const toolUsesInlinePrompt = (tool: DetectedTool): boolean =>
|
||||
toolAcceptsInlinePrompt(tool.id) || tool.acceptsInlinePrompt === true;
|
||||
|
||||
const ACCESS_LABELS: Record<ExternalToolAccess, string> = {
|
||||
'read-only': 'Read only',
|
||||
'workspace-write': 'Workspace write',
|
||||
native: 'Native permissions',
|
||||
};
|
||||
|
||||
const defaultAccessForTool = (tool: DetectedTool): ExternalToolAccess | null => {
|
||||
const modes = tool.permissionModes ?? [];
|
||||
return modes.includes('read-only') ? 'read-only' : (modes[0] ?? null);
|
||||
};
|
||||
|
||||
const toolCanRunCapturedTask = (tool: DetectedTool): boolean =>
|
||||
tool.installed &&
|
||||
toolCanLaunch(tool) &&
|
||||
tool.capabilities?.headlessTask === true &&
|
||||
(tool.permissionModes?.length ?? 0) > 0;
|
||||
|
||||
const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: LauncherAppProps = {}) => {
|
||||
// ADR-0002: Waggle Room is hidden in v1 (memory feature map). Launch, watch
|
||||
// and stop stay.
|
||||
const roomShown = hasMemoryFeature('room');
|
||||
const LauncherApp = ({ activeWorkspaceId }: LauncherAppProps = {}) => {
|
||||
const cachedDetection = launcherRouteCache.read('tools');
|
||||
const [detection, setDetection] = useState<DetectionResult | null>(cachedDetection ?? null);
|
||||
const [loading, setLoading] = useState(() => !launcherRouteCache.hasResolved('tools'));
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [activeAction, setActiveAction] = useState<ActionState | null>(null);
|
||||
/** Tool whose launch or stop request is in flight. */
|
||||
const [activeToolId, setActiveToolId] = useState<string | null>(null);
|
||||
const [lastResult, setLastResult] = useState<ActionResult | null>(null);
|
||||
const [prompt, setPrompt] = useState('');
|
||||
const [taskToolId, setTaskToolId] = useState<string | null>(null);
|
||||
const [taskPrompt, setTaskPrompt] = useState('');
|
||||
const [taskWorkspaceIds, setTaskWorkspaceIds] = useState<string[]>([]);
|
||||
const [taskParticipants, setTaskParticipants] = useState<Record<string, ExternalToolAccess>>({});
|
||||
/**
|
||||
* AI-OS Phase 4 polish — set of tool ids currently running (at
|
||||
* least one tracked + alive pid). Used to render the 'Running'
|
||||
@@ -225,13 +187,12 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche
|
||||
const pids = pidsByTool.get(tool.id) ?? [];
|
||||
const pid = pids[0];
|
||||
if (!pid) return;
|
||||
setActiveAction({ toolId: tool.id, action: 'launch' }); // reuse launch spinner slot
|
||||
setActiveToolId(tool.id);
|
||||
setLastResult(null);
|
||||
try {
|
||||
const r = await adapter.killTool(pid);
|
||||
setLastResult({
|
||||
toolId: tool.id,
|
||||
action: 'launch',
|
||||
ok: r.ok,
|
||||
message: r.ok
|
||||
? `Stopped ${tool.displayName} (pid ${r.pid}, ${r.reason})`
|
||||
@@ -252,12 +213,11 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche
|
||||
} catch (err) {
|
||||
setLastResult({
|
||||
toolId: tool.id,
|
||||
action: 'launch',
|
||||
ok: false,
|
||||
message: err instanceof Error ? err.message : 'Stop failed',
|
||||
});
|
||||
} finally {
|
||||
setActiveAction(null);
|
||||
setActiveToolId(null);
|
||||
}
|
||||
},
|
||||
[pidsByTool],
|
||||
@@ -265,14 +225,12 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche
|
||||
|
||||
const launchSelectedTool = useCallback(
|
||||
async (tool: DetectedTool) => {
|
||||
const action = 'launch';
|
||||
setActiveAction({ toolId: tool.id, action });
|
||||
setActiveToolId(tool.id);
|
||||
setLastResult(null);
|
||||
try {
|
||||
if (!tool.installedPath) {
|
||||
setLastResult({
|
||||
toolId: tool.id,
|
||||
action,
|
||||
ok: false,
|
||||
message: 'Tool not installed. Cannot launch.',
|
||||
});
|
||||
@@ -296,7 +254,6 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche
|
||||
const promptNote = (args || sendsRawPrompt) ? ' with prompt' : '';
|
||||
setLastResult({
|
||||
toolId: tool.id,
|
||||
action,
|
||||
ok: r.ok,
|
||||
message: r.ok
|
||||
? `Launched ${tool.displayName}${promptNote} (pid ${r.pid})`
|
||||
@@ -310,95 +267,17 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche
|
||||
} catch (err) {
|
||||
setLastResult({
|
||||
toolId: tool.id,
|
||||
action,
|
||||
ok: false,
|
||||
message: err instanceof Error ? err.message : 'Action failed',
|
||||
});
|
||||
} finally {
|
||||
setActiveAction(null);
|
||||
setActiveToolId(null);
|
||||
}
|
||||
},
|
||||
[activeWorkspaceId, prompt, watchMode],
|
||||
);
|
||||
|
||||
const tools = useMemo<DetectedTool[]>(() => detection?.tools ?? [], [detection]);
|
||||
const availableWorkspaces = useMemo(
|
||||
() => workspaces.filter((workspace) => workspace.status !== 'archived'),
|
||||
[workspaces],
|
||||
);
|
||||
const taskCapableTools = useMemo(
|
||||
() => tools.filter(toolCanRunCapturedTask),
|
||||
[tools],
|
||||
);
|
||||
|
||||
const openTaskComposer = useCallback((tool: DetectedTool) => {
|
||||
const defaultAccess = defaultAccessForTool(tool);
|
||||
if (!defaultAccess) return;
|
||||
const defaultWorkspace = availableWorkspaces.find((workspace) => workspace.id === activeWorkspaceId)
|
||||
?? availableWorkspaces[0];
|
||||
setTaskToolId(tool.id);
|
||||
setTaskPrompt('');
|
||||
setTaskWorkspaceIds(defaultWorkspace ? [defaultWorkspace.id] : []);
|
||||
setTaskParticipants({ [tool.id]: defaultAccess });
|
||||
setLastResult(null);
|
||||
}, [activeWorkspaceId, availableWorkspaces]);
|
||||
|
||||
const toggleTaskParticipant = useCallback((tool: DetectedTool) => {
|
||||
const defaultAccess = defaultAccessForTool(tool);
|
||||
if (!defaultAccess) return;
|
||||
setTaskParticipants((current) => {
|
||||
if (current[tool.id]) {
|
||||
const next = { ...current };
|
||||
delete next[tool.id];
|
||||
return next;
|
||||
}
|
||||
return { ...current, [tool.id]: defaultAccess };
|
||||
});
|
||||
}, []);
|
||||
|
||||
const toggleTaskWorkspace = useCallback((workspaceId: string) => {
|
||||
setTaskWorkspaceIds((current) => current.includes(workspaceId)
|
||||
? current.filter((id) => id !== workspaceId)
|
||||
: [...current, workspaceId]);
|
||||
}, []);
|
||||
|
||||
const runCapturedTask = useCallback(async (tool: DetectedTool) => {
|
||||
const task = taskPrompt.trim();
|
||||
const participants = taskCapableTools.flatMap((candidate) => {
|
||||
const access = taskParticipants[candidate.id];
|
||||
return access ? [{ toolId: candidate.id, access }] : [];
|
||||
});
|
||||
if (!task || participants.length === 0 || taskWorkspaceIds.length === 0) return;
|
||||
setActiveAction({ toolId: tool.id, action: 'run' });
|
||||
setLastResult(null);
|
||||
try {
|
||||
const result = await adapter.runExternalToolTask({
|
||||
participants,
|
||||
workspaceIds: taskWorkspaceIds,
|
||||
prompt: task,
|
||||
});
|
||||
setLastResult({
|
||||
toolId: tool.id,
|
||||
action: 'run',
|
||||
ok: true,
|
||||
message: `Started ${participants.length} agent${participants.length === 1 ? '' : 's'} across ${taskWorkspaceIds.length} workspace${taskWorkspaceIds.length === 1 ? '' : 's'} (${result.runs.length} worker run${result.runs.length === 1 ? '' : 's'}). Opening Room.`,
|
||||
});
|
||||
setTaskPrompt('');
|
||||
setTaskToolId(null);
|
||||
setTaskParticipants({});
|
||||
onOpenRoom?.(result.roomId);
|
||||
} catch (err) {
|
||||
setLastResult({
|
||||
toolId: tool.id,
|
||||
action: 'run',
|
||||
ok: false,
|
||||
message: err instanceof Error ? err.message : 'Captured task failed to start',
|
||||
});
|
||||
} finally {
|
||||
setActiveAction(null);
|
||||
}
|
||||
}, [onOpenRoom, taskCapableTools, taskParticipants, taskPrompt, taskWorkspaceIds]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full bg-background text-foreground">
|
||||
{/* Header — title + refresh */}
|
||||
@@ -516,7 +395,7 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche
|
||||
)}
|
||||
{tools.map((tool) => {
|
||||
const launchable = toolCanLaunch(tool);
|
||||
const isActive = activeAction?.toolId === tool.id;
|
||||
const isActive = activeToolId === tool.id;
|
||||
return (
|
||||
<div
|
||||
key={tool.id}
|
||||
@@ -576,168 +455,36 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche
|
||||
|
||||
{/* Actions row */}
|
||||
{launchable && tool.installed && (
|
||||
<>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="h-7 text-[11px]"
|
||||
onClick={() => launchSelectedTool(tool)}
|
||||
disabled={isActive}
|
||||
>
|
||||
{isActive ? (
|
||||
<Loader2 className="w-3 h-3 animate-spin mr-1" />
|
||||
) : (
|
||||
<Play className="w-3 h-3 mr-1" />
|
||||
)}
|
||||
Launch
|
||||
</Button>
|
||||
{runningTools.has(tool.id) && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
variant="ghost"
|
||||
className="h-7 text-[11px]"
|
||||
onClick={() => launchSelectedTool(tool)}
|
||||
style={{ color: 'var(--risk)' }}
|
||||
onClick={() => stopTool(tool)}
|
||||
disabled={isActive}
|
||||
title="Send SIGTERM (escalates to SIGKILL after 3s if needed)"
|
||||
>
|
||||
{isActive && activeAction?.action === 'launch' ? (
|
||||
<Loader2 className="w-3 h-3 animate-spin mr-1" />
|
||||
) : (
|
||||
<Play className="w-3 h-3 mr-1" />
|
||||
)}
|
||||
Launch
|
||||
<Square className="w-3 h-3 mr-1" />
|
||||
Stop
|
||||
</Button>
|
||||
{roomShown && toolCanRunCapturedTask(tool) && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="default"
|
||||
className="h-7 text-[11px]"
|
||||
onClick={() => openTaskComposer(tool)}
|
||||
disabled={isActive}
|
||||
>
|
||||
{isActive && activeAction?.action === 'run' ? (
|
||||
<Loader2 className="w-3 h-3 animate-spin mr-1" />
|
||||
) : (
|
||||
<Workflow className="w-3 h-3 mr-1" />
|
||||
)}
|
||||
Run task
|
||||
</Button>
|
||||
)}
|
||||
{runningTools.has(tool.id) && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-7 text-[11px]"
|
||||
style={{ color: 'var(--risk)' }}
|
||||
onClick={() => stopTool(tool)}
|
||||
disabled={isActive}
|
||||
title="Send SIGTERM (escalates to SIGKILL after 3s if needed)"
|
||||
>
|
||||
<Square className="w-3 h-3 mr-1" />
|
||||
Stop
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{roomShown && taskToolId === tool.id && toolCanRunCapturedTask(tool) && (
|
||||
<div
|
||||
className="rounded-lg border border-primary/30 bg-primary/5 p-3 space-y-3"
|
||||
data-testid={`captured-task-${tool.id}`}
|
||||
>
|
||||
<div>
|
||||
<p className="text-xs font-display font-semibold text-foreground">
|
||||
Captured agent team · started from {tool.displayName}
|
||||
</p>
|
||||
<p className="text-[11px] text-muted-foreground mt-0.5">
|
||||
Each selected agent runs once per workspace. Progress, results, and memory return to one Room.
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<label htmlFor={`captured-task-prompt-${tool.id}`} className="text-[11px] font-medium text-foreground">
|
||||
Task
|
||||
</label>
|
||||
<textarea
|
||||
id={`captured-task-prompt-${tool.id}`}
|
||||
aria-label={`Task for ${tool.displayName}`}
|
||||
value={taskPrompt}
|
||||
onChange={(event) => setTaskPrompt(event.target.value)}
|
||||
rows={3}
|
||||
placeholder="Describe the result this agent should deliver…"
|
||||
className="w-full text-xs bg-background border border-border/50 rounded p-2 resize-y min-h-[64px] max-h-[220px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
/>
|
||||
</div>
|
||||
<fieldset className="space-y-1.5">
|
||||
<legend className="text-[11px] font-medium text-foreground">Agents</legend>
|
||||
<div className="space-y-1.5">
|
||||
{taskCapableTools.map((candidate) => {
|
||||
const access = taskParticipants[candidate.id];
|
||||
return (
|
||||
<div
|
||||
key={candidate.id}
|
||||
className="flex flex-wrap items-center justify-between gap-2 rounded border border-border/40 bg-background/60 px-2 py-1.5"
|
||||
>
|
||||
<label className="flex items-center gap-2 text-[11px] text-foreground cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={candidate.displayName}
|
||||
checked={access !== undefined}
|
||||
onChange={() => toggleTaskParticipant(candidate)}
|
||||
/>
|
||||
<span>{candidate.displayName}</span>
|
||||
</label>
|
||||
{access && (
|
||||
<select
|
||||
aria-label={`Access for ${candidate.displayName}`}
|
||||
value={access}
|
||||
onChange={(event) => setTaskParticipants((current) => ({
|
||||
...current,
|
||||
[candidate.id]: event.target.value as ExternalToolAccess,
|
||||
}))}
|
||||
className="h-7 rounded border border-border/50 bg-background px-2 text-[11px] text-foreground"
|
||||
>
|
||||
{(candidate.permissionModes ?? []).map((mode) => (
|
||||
<option key={mode} value={mode}>{ACCESS_LABELS[mode]}</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset className="space-y-1.5">
|
||||
<legend className="text-[11px] font-medium text-foreground">Workspaces</legend>
|
||||
{availableWorkspaces.length > 0 ? (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-1.5">
|
||||
{availableWorkspaces.map((workspace) => (
|
||||
<label
|
||||
key={workspace.id}
|
||||
className="flex items-center gap-2 rounded border border-border/40 bg-background/60 px-2 py-1.5 text-[11px] text-foreground cursor-pointer"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={taskWorkspaceIds.includes(workspace.id)}
|
||||
onChange={() => toggleTaskWorkspace(workspace.id)}
|
||||
/>
|
||||
<span className="truncate">{workspace.name}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-[11px] text-muted-foreground">Create a workspace before running a captured task.</p>
|
||||
)}
|
||||
</fieldset>
|
||||
<div className="flex items-center justify-end gap-1.5">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-7 text-[11px]"
|
||||
onClick={() => setTaskToolId(null)}
|
||||
disabled={isActive}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
className="h-7 text-[11px]"
|
||||
onClick={() => void runCapturedTask(tool)}
|
||||
disabled={isActive || !taskPrompt.trim() || Object.keys(taskParticipants).length === 0 || taskWorkspaceIds.length === 0}
|
||||
>
|
||||
{isActive && activeAction?.action === 'run' ? (
|
||||
<Loader2 className="w-3 h-3 animate-spin mr-1" />
|
||||
) : (
|
||||
<Workflow className="w-3 h-3 mr-1" />
|
||||
)}
|
||||
Start in Room
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
</div>
|
||||
)}
|
||||
{launchable && !tool.installed && (
|
||||
<div className="text-[11px] text-muted-foreground">
|
||||
|
||||
@@ -34,7 +34,7 @@ import type {
|
||||
ConnectorDefinition, ConnectorHealth, McpInstance, ExtensionType,
|
||||
InterpretResult, ResolvedAction,
|
||||
CollaborationRun, CollaborationRunEvent, CollaborationRunSnapshot,
|
||||
CollaborationRunControl, ExternalToolAccess, ToolDetectionResult,
|
||||
CollaborationRunControl, ToolDetectionResult,
|
||||
} from '@waggle/shared';
|
||||
|
||||
export interface SpawnAgentResult {
|
||||
@@ -1927,26 +1927,6 @@ class LocalAdapter {
|
||||
return body.run;
|
||||
}
|
||||
|
||||
async runExternalToolTask(data: {
|
||||
workspaceIds: string[];
|
||||
prompt: string;
|
||||
timeoutMs?: number;
|
||||
sessionIds?: Record<string, string>;
|
||||
} & (
|
||||
| { toolId: string; access?: ExternalToolAccess; participants?: never }
|
||||
| {
|
||||
participants: Array<{ toolId: string; access: ExternalToolAccess }>;
|
||||
toolId?: never;
|
||||
access?: never;
|
||||
}
|
||||
)): Promise<{
|
||||
roomId: string;
|
||||
runs: Array<{ runId: string; workspaceId: string; toolId?: string; status: string; statusUrl: string }>;
|
||||
}> {
|
||||
const res = await this.fetch('/api/tools/run', { method: 'POST', body: JSON.stringify(data) });
|
||||
return res.json();
|
||||
}
|
||||
|
||||
async listAgents(): Promise<Agent[]> {
|
||||
const res = await this.fetch('/api/agents');
|
||||
if (!res.ok) throw new Error(`listAgents failed: ${res.status}`);
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
* claude-code → ['--print', prompt]
|
||||
* openclaw → ['--print', prompt] (Claude Code fork)
|
||||
* codex → [prompt] (positional arg)
|
||||
* hermes → null (captured-task API only)
|
||||
* hermes → null (no verified inline prompt)
|
||||
* hermes-desktop → null (GUI only)
|
||||
* cursor → null (folder-based; no CLI prompt)
|
||||
* claude-desktop → null (GUI only)
|
||||
@@ -65,8 +65,7 @@ export function promptArgsForTool(toolId: string, prompt: string): string[] | nu
|
||||
return [p];
|
||||
|
||||
// GUI-only tools and Hermes interactive launch: no verified inline-prompt
|
||||
// surface. Hermes captured tasks use the shared headless task contract,
|
||||
// not this dock-launch helper.
|
||||
// surface.
|
||||
// cursor: opens a folder (`cursor /path`), no --prompt flag.
|
||||
// claude-desktop / codex-desktop: GUI binaries with no
|
||||
// prompt-from-CLI handoff documented.
|
||||
|
||||
@@ -3,10 +3,11 @@
|
||||
*
|
||||
* v1 memory is facts, search and the user profile. The knowledge graph follows
|
||||
* the server's memory capability map (`GET /api/memory/capabilities`), which
|
||||
* reports it unavailable in v1. History import, wiki and Room are hidden in v1
|
||||
* by decision, whatever the store supports. Their screens stay in the code and
|
||||
* reports it unavailable in v1. History import and wiki are hidden in v1 by
|
||||
* decision, whatever the store supports. Their screens stay in the code and
|
||||
* every surface that offers one checks this module first. Coding-agent hooks
|
||||
* and the memory MCP server left with their packages (P2.2).
|
||||
* and the memory MCP server left with their packages (P2.2); Waggle Room's
|
||||
* coding-agent tasks left with their runtime.
|
||||
*/
|
||||
import { useEffect, useSyncExternalStore } from 'react';
|
||||
import { adapter } from '@/lib/adapter';
|
||||
@@ -19,8 +20,6 @@ export interface MemoryFeatures {
|
||||
importHistory: boolean;
|
||||
/** Compiled wiki pages. */
|
||||
wiki: boolean;
|
||||
/** Waggle Room: coding agents started as a team that shares one Room. */
|
||||
room: boolean;
|
||||
}
|
||||
|
||||
export type MemoryFeature = keyof MemoryFeatures;
|
||||
@@ -29,7 +28,6 @@ export type MemoryFeature = keyof MemoryFeatures;
|
||||
const HIDDEN_IN_V1: Readonly<Record<Exclude<MemoryFeature, 'knowledgeGraph'>, false>> = {
|
||||
importHistory: false,
|
||||
wiki: false,
|
||||
room: false,
|
||||
};
|
||||
|
||||
let current: MemoryCapabilitiesResponse | null = null;
|
||||
|
||||
@@ -2,18 +2,12 @@
|
||||
import LauncherApp from '@/components/os/apps/LauncherApp';
|
||||
import SurfaceBoundary from './SurfaceBoundary';
|
||||
import { useShell } from '@/providers/ShellContext';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
const LauncherRoute = () => {
|
||||
const { activeWorkspaceId, workspaces } = useShell();
|
||||
const navigate = useNavigate();
|
||||
const { activeWorkspaceId } = useShell();
|
||||
return (
|
||||
<SurfaceBoundary appName="Tool Launcher">
|
||||
<LauncherApp
|
||||
activeWorkspaceId={activeWorkspaceId ?? undefined}
|
||||
workspaces={workspaces}
|
||||
onOpenRoom={(roomId) => navigate(`/room?room=${encodeURIComponent(roomId)}`)}
|
||||
/>
|
||||
<LauncherApp activeWorkspaceId={activeWorkspaceId ?? undefined} />
|
||||
</SurfaceBoundary>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -40,7 +40,7 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe('memory feature map (v1 defaults)', () => {
|
||||
it.each<MemoryFeature>(['knowledgeGraph', 'importHistory', 'wiki', 'room'])(
|
||||
it.each<MemoryFeature>(['knowledgeGraph', 'importHistory', 'wiki'])(
|
||||
'%s is hidden',
|
||||
(feature) => {
|
||||
expect(hasMemoryFeature(feature)).toBe(false);
|
||||
@@ -66,9 +66,9 @@ describe('memory feature map from the server capabilities', () => {
|
||||
expect(isMemoryViewAvailable('graph')).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps import, wiki, hooks, Room and the memory MCP hidden whatever the store reports', () => {
|
||||
it('keeps import and wiki hidden whatever the store reports', () => {
|
||||
setMemoryCapabilities(report(true));
|
||||
for (const feature of ['importHistory', 'wiki', 'room'] as const) {
|
||||
for (const feature of ['importHistory', 'wiki'] as const) {
|
||||
expect(hasMemoryFeature(feature), feature).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,660 +0,0 @@
|
||||
import { execFile } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import type {
|
||||
ExternalToolAccess,
|
||||
ToolManifest,
|
||||
ToolOutputDialect,
|
||||
ToolTaskSpec,
|
||||
} from '@waggle/shared';
|
||||
import { resolveToolCommandInvocation } from './tool-command.js';
|
||||
import { stripAnsi } from './tool-output-buffer.js';
|
||||
import { buildExternalProcessEnv } from './external-process-env.js';
|
||||
import { spawnSidecarOwnedProcess } from './sidecar-owned-process.js';
|
||||
|
||||
const MAX_STDOUT = 256 * 1024;
|
||||
const MAX_STDERR = 64 * 1024;
|
||||
const MAX_EVENT_TEXT = 8_000;
|
||||
const DEFAULT_TIMEOUT_MS = 10 * 60 * 1_000;
|
||||
const MAX_TIMEOUT_MS = 30 * 60 * 1_000;
|
||||
const DEFAULT_STALL_AFTER_MS = 120_000;
|
||||
const MIN_STALL_AFTER_MS = 30_000;
|
||||
const TREE_KILL_TIMEOUT_MS = 5_000;
|
||||
const TERMINATION_SETTLE_MS = 2_000;
|
||||
|
||||
export type ExternalRunEventType =
|
||||
| 'started' | 'progress' | 'message' | 'tool'
|
||||
| 'completed' | 'failed' | 'cancelled' | 'timed_out';
|
||||
|
||||
export interface ExternalRunEvent {
|
||||
runId: string;
|
||||
roomId: string;
|
||||
workspaceId: string;
|
||||
toolId: string;
|
||||
seq: number;
|
||||
type: ExternalRunEventType;
|
||||
timestamp: string;
|
||||
text?: string;
|
||||
sessionId?: string;
|
||||
pid?: number;
|
||||
stalled?: boolean;
|
||||
}
|
||||
|
||||
export interface ExternalToolRunRequest {
|
||||
manifest: ToolManifest;
|
||||
binary: string;
|
||||
workspaceId: string;
|
||||
workspacePath: string;
|
||||
runId: string;
|
||||
roomId: string;
|
||||
prompt: string;
|
||||
access: ExternalToolAccess;
|
||||
timeoutMs?: number;
|
||||
stallAfterMs?: number;
|
||||
/** Native session id for a resume attempt. */
|
||||
sessionId?: string;
|
||||
/** Required by managed-agent adapters such as OpenClaw. */
|
||||
managedAgentId?: string;
|
||||
/** Narrow sidecar transport credential for this run's WaggleDance Room. */
|
||||
dance?: { url: string; token: string; nodePath: string; cliEntry: string };
|
||||
/** Canonical shared memory root used by hooks and the collaboration CLI. */
|
||||
dataDir?: string;
|
||||
signal?: AbortSignal;
|
||||
onEvent?: (event: ExternalRunEvent) => void;
|
||||
}
|
||||
|
||||
export interface ExternalToolRunResult {
|
||||
status: 'completed' | 'failed' | 'cancelled' | 'timed_out';
|
||||
exitCode: number | null;
|
||||
summary: string;
|
||||
error?: string;
|
||||
sessionId?: string;
|
||||
stdoutTail: string;
|
||||
stderrTail: string;
|
||||
durationMs: number;
|
||||
}
|
||||
|
||||
export interface ExternalProcessHandle {
|
||||
pid: number;
|
||||
exitCode: number | null;
|
||||
signalCode: NodeJS.Signals | null;
|
||||
stdout: { on(event: 'data', cb: (chunk: Buffer | string) => void): void };
|
||||
stderr: { on(event: 'data', cb: (chunk: Buffer | string) => void): void };
|
||||
stdin: { write(value: string): void; end(): void };
|
||||
kill(signal?: NodeJS.Signals | number): boolean;
|
||||
once(event: 'error', cb: (error: Error) => void): void;
|
||||
once(event: 'exit', cb: (code: number | null) => void): void;
|
||||
}
|
||||
|
||||
export interface ExternalToolRunnerDeps {
|
||||
platform?: NodeJS.Platform;
|
||||
baseEnv?: NodeJS.ProcessEnv;
|
||||
now?: () => number;
|
||||
resolveWorkspacePath?: (workspacePath: string) => string;
|
||||
createPromptFile?: (prompt: string) => { path: string; cleanup: () => void };
|
||||
spawnProcess?: (
|
||||
binary: string,
|
||||
args: string[],
|
||||
options: { cwd: string; env: NodeJS.ProcessEnv },
|
||||
) => ExternalProcessHandle;
|
||||
killTree?: (pid: number, platform: NodeJS.Platform) => Promise<void>;
|
||||
}
|
||||
|
||||
interface ParseState {
|
||||
finalText: string;
|
||||
sessionId?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export async function runExternalTool(
|
||||
request: ExternalToolRunRequest,
|
||||
deps: ExternalToolRunnerDeps = {},
|
||||
): Promise<ExternalToolRunResult> {
|
||||
const task = requireTaskSpec(request.manifest, request.access, request.sessionId);
|
||||
const platform = deps.platform ?? process.platform;
|
||||
const now = deps.now ?? Date.now;
|
||||
const startedAt = now();
|
||||
const workspacePath = (deps.resolveWorkspacePath ?? defaultResolveWorkspacePath)(request.workspacePath);
|
||||
if (task.workspaceBinding === 'managed-agent' && !request.managedAgentId) {
|
||||
throw new Error(`Tool ${request.manifest.id} requires a managed workspace agent`);
|
||||
}
|
||||
const timeoutMs = Math.max(1_000, Math.min(request.timeoutMs ?? DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS));
|
||||
const requestedStallAfterMs = Math.max(
|
||||
MIN_STALL_AFTER_MS,
|
||||
request.stallAfterMs ?? DEFAULT_STALL_AFTER_MS,
|
||||
);
|
||||
const stallAfterMs = requestedStallAfterMs < timeoutMs ? requestedStallAfterMs : undefined;
|
||||
const promptFile = task.promptTransport === 'temp-file'
|
||||
? (deps.createPromptFile ?? defaultCreatePromptFile)(request.prompt)
|
||||
: undefined;
|
||||
let promptCleaned = false;
|
||||
const cleanupPromptFile = () => {
|
||||
if (promptCleaned) return;
|
||||
promptCleaned = true;
|
||||
try { promptFile?.cleanup(); } catch { /* best-effort secure temp cleanup */ }
|
||||
};
|
||||
const args = renderArgs(
|
||||
request.sessionId && task.resumeArgvTemplate ? task.resumeArgvTemplate : task.argvTemplate,
|
||||
task,
|
||||
request,
|
||||
workspacePath,
|
||||
promptFile?.path,
|
||||
timeoutMs,
|
||||
);
|
||||
const env = buildExternalToolEnv(deps.baseEnv ?? process.env, request, workspacePath, platform);
|
||||
const spawnProcess = deps.spawnProcess ?? defaultSpawnProcess;
|
||||
const killTree = deps.killTree ?? defaultKillTree;
|
||||
const parseState: ParseState = { finalText: '' };
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
let stdoutRemainder = '';
|
||||
let seq = 0;
|
||||
let abortRequested = request.signal?.aborted ?? false;
|
||||
let timedOut = false;
|
||||
let lastEventAtMs = startedAt;
|
||||
let stalledEpisode = false;
|
||||
|
||||
const emit = (type: ExternalRunEventType, text?: string, pid?: number, stalled?: boolean) => {
|
||||
const emittedAt = now();
|
||||
if (stalled !== true) lastEventAtMs = emittedAt;
|
||||
request.onEvent?.({
|
||||
runId: request.runId,
|
||||
roomId: request.roomId,
|
||||
workspaceId: request.workspaceId,
|
||||
toolId: request.manifest.id,
|
||||
seq: ++seq,
|
||||
type,
|
||||
timestamp: new Date(emittedAt).toISOString(),
|
||||
...(text ? { text: truncate(redact(text, env), MAX_EVENT_TEXT) } : {}),
|
||||
...(parseState.sessionId ? { sessionId: parseState.sessionId } : {}),
|
||||
...(pid ? { pid } : {}),
|
||||
...(stalled !== undefined ? { stalled } : {}),
|
||||
});
|
||||
};
|
||||
|
||||
if (abortRequested) {
|
||||
cleanupPromptFile();
|
||||
emit('cancelled', 'Cancelled before launch');
|
||||
return terminalResult('cancelled', null, '', '', '', now() - startedAt);
|
||||
}
|
||||
|
||||
let child: ExternalProcessHandle;
|
||||
try {
|
||||
child = spawnProcess(request.binary, args, { cwd: workspacePath, env });
|
||||
} catch (err) {
|
||||
cleanupPromptFile();
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
emit('failed', message);
|
||||
return terminalResult('failed', null, message, '', message, now() - startedAt);
|
||||
}
|
||||
emit('started', `Started ${request.manifest.displayName}`, child.pid);
|
||||
|
||||
const stallTimer = stallAfterMs === undefined ? undefined : setInterval(() => {
|
||||
if (abortRequested || timedOut) return;
|
||||
const idleMs = now() - lastEventAtMs;
|
||||
if (!stalledEpisode && idleMs >= stallAfterMs) {
|
||||
stalledEpisode = true;
|
||||
emit('progress', `[stalled] no output for ${Math.floor(idleMs / 1_000)}s`, undefined, true);
|
||||
}
|
||||
}, Math.min(stallAfterMs, 1_000));
|
||||
stallTimer?.unref();
|
||||
|
||||
const recordOutputActivity = () => {
|
||||
const wasStalled = stalledEpisode;
|
||||
lastEventAtMs = now();
|
||||
if (wasStalled) {
|
||||
stalledEpisode = false;
|
||||
emit('progress', '[recovered] output resumed', undefined, false);
|
||||
}
|
||||
};
|
||||
|
||||
child.stdout.on('data', (chunk) => {
|
||||
recordOutputActivity();
|
||||
const text = chunk.toString();
|
||||
stdout = appendTail(stdout, text, MAX_STDOUT);
|
||||
stdoutRemainder += text;
|
||||
const lines = stdoutRemainder.split(/\r?\n/);
|
||||
stdoutRemainder = lines.pop() ?? '';
|
||||
for (const line of lines) parseLine(task.outputDialect, line, parseState, emit);
|
||||
});
|
||||
child.stderr.on('data', (chunk) => {
|
||||
recordOutputActivity();
|
||||
const text = chunk.toString();
|
||||
stderr = appendTail(stderr, text, MAX_STDERR);
|
||||
const progress = stripAnsi(text).trim();
|
||||
if (progress) emit('progress', progress);
|
||||
});
|
||||
return await new Promise<ExternalToolRunResult>((resolve) => {
|
||||
let settled = false;
|
||||
let terminationIntent: 'cancelled' | 'timed_out' | null = null;
|
||||
let treeKillDeadline: NodeJS.Timeout | undefined;
|
||||
let settlementTimer: NodeJS.Timeout | undefined;
|
||||
let timeout: NodeJS.Timeout | undefined;
|
||||
const finish = (exitCode: number | null, spawnError?: Error) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
if (timeout) clearTimeout(timeout);
|
||||
if (treeKillDeadline) clearTimeout(treeKillDeadline);
|
||||
if (settlementTimer) clearTimeout(settlementTimer);
|
||||
if (stallTimer) clearInterval(stallTimer);
|
||||
request.signal?.removeEventListener('abort', abortHandler);
|
||||
if (stdoutRemainder.trim()) parseLine(task.outputDialect, stdoutRemainder, parseState, emit);
|
||||
if (task.outputDialect === 'json' || task.outputDialect === 'openclaw-json') {
|
||||
parseWholeJson(stdout, parseState, emit);
|
||||
}
|
||||
if (task.outputDialect === 'hermes-text') {
|
||||
parseState.sessionId = extractSessionId(stripAnsi(stderr)) ?? parseState.sessionId;
|
||||
}
|
||||
cleanupPromptFile();
|
||||
|
||||
if (
|
||||
task.outputDialect === 'claude-stream-json' &&
|
||||
exitCode === 0 &&
|
||||
!timedOut &&
|
||||
!abortRequested &&
|
||||
!spawnError &&
|
||||
!parseState.finalText &&
|
||||
!parseState.error
|
||||
) {
|
||||
parseState.error = 'Claude Code completed without a final response';
|
||||
}
|
||||
|
||||
const cleanStdout = redact(stdout, env);
|
||||
const cleanStderr = redact(stderr, env);
|
||||
let status: ExternalToolRunResult['status'];
|
||||
if (timedOut) status = 'timed_out';
|
||||
else if (abortRequested) status = 'cancelled';
|
||||
else if (spawnError || exitCode !== 0 || parseState.error) status = 'failed';
|
||||
else status = 'completed';
|
||||
const terminalError = status === 'failed'
|
||||
? truncate(stripAnsi(
|
||||
(parseState.error ? redact(parseState.error, env) : '') ||
|
||||
(spawnError ? redact(spawnError.message, env) : '') ||
|
||||
cleanStderr.trim() ||
|
||||
(exitCode !== null && exitCode !== 0
|
||||
? `${request.manifest.displayName} exited with code ${exitCode}`
|
||||
: ''),
|
||||
).trim(), MAX_STDERR)
|
||||
: undefined;
|
||||
const stdoutFallback = task.outputDialect === 'claude-stream-json' ? '' : cleanStdout.trim();
|
||||
const summary = truncate(
|
||||
stripAnsi(
|
||||
redact(parseState.finalText, env) ||
|
||||
stdoutFallback ||
|
||||
cleanStderr.trim() ||
|
||||
terminalError ||
|
||||
'',
|
||||
).trim(),
|
||||
MAX_STDOUT,
|
||||
);
|
||||
emit(status, status === 'completed' ? summary : (terminalError || summary));
|
||||
resolve({
|
||||
...terminalResult(status, exitCode, summary, cleanStdout, cleanStderr, now() - startedAt),
|
||||
...(terminalError ? { error: terminalError } : {}),
|
||||
...(parseState.sessionId ? { sessionId: parseState.sessionId } : {}),
|
||||
});
|
||||
};
|
||||
|
||||
const appendCleanupError = (error: unknown) => {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
stderr = appendTail(stderr, message, MAX_STDERR);
|
||||
};
|
||||
const childHasExited = () => child.exitCode !== null || child.signalCode !== null;
|
||||
const forceRootKill = () => {
|
||||
if (settled || childHasExited()) return;
|
||||
try {
|
||||
if (!child.kill('SIGKILL')) appendCleanupError('Root process refused SIGKILL');
|
||||
} catch (error) {
|
||||
appendCleanupError(error);
|
||||
}
|
||||
};
|
||||
const scheduleForcedSettlement = () => {
|
||||
if (settled || settlementTimer) return;
|
||||
settlementTimer = setTimeout(() => finish(child.exitCode), TERMINATION_SETTLE_MS);
|
||||
};
|
||||
const requestTermination = (intent: 'cancelled' | 'timed_out') => {
|
||||
if (settled || terminationIntent) return;
|
||||
if (childHasExited()) {
|
||||
finish(child.exitCode);
|
||||
return;
|
||||
}
|
||||
terminationIntent = intent;
|
||||
abortRequested = intent === 'cancelled';
|
||||
timedOut = intent === 'timed_out';
|
||||
if (intent === 'cancelled' && timeout) {
|
||||
clearTimeout(timeout);
|
||||
timeout = undefined;
|
||||
}
|
||||
|
||||
let treeAttemptFinished = false;
|
||||
const finishTreeAttempt = (fallbackToRoot: boolean, error?: unknown) => {
|
||||
if (settled || treeAttemptFinished) return;
|
||||
treeAttemptFinished = true;
|
||||
if (treeKillDeadline) {
|
||||
clearTimeout(treeKillDeadline);
|
||||
treeKillDeadline = undefined;
|
||||
}
|
||||
if (error !== undefined) appendCleanupError(error);
|
||||
if (fallbackToRoot) forceRootKill();
|
||||
scheduleForcedSettlement();
|
||||
};
|
||||
|
||||
treeKillDeadline = setTimeout(() => {
|
||||
finishTreeAttempt(true, new Error(`Process-tree cleanup exceeded ${TREE_KILL_TIMEOUT_MS}ms`));
|
||||
}, TREE_KILL_TIMEOUT_MS);
|
||||
try {
|
||||
void killTree(child.pid, platform).then(
|
||||
() => finishTreeAttempt(false),
|
||||
(error) => finishTreeAttempt(true, error),
|
||||
);
|
||||
} catch (error) {
|
||||
finishTreeAttempt(true, error);
|
||||
}
|
||||
};
|
||||
const abortHandler = () => requestTermination('cancelled');
|
||||
|
||||
child.once('error', (error) => finish(null, error));
|
||||
child.once('exit', (code) => finish(code));
|
||||
timeout = setTimeout(() => requestTermination('timed_out'), timeoutMs);
|
||||
request.signal?.addEventListener('abort', abortHandler, { once: true });
|
||||
// Close the spawn/listener race: an abort can land after the pre-launch
|
||||
// check but before the listener above is attached.
|
||||
if (request.signal?.aborted) abortHandler();
|
||||
if (!abortRequested && task.promptTransport === 'stdin') child.stdin.write(request.prompt);
|
||||
child.stdin.end();
|
||||
});
|
||||
}
|
||||
|
||||
export function buildExternalToolEnv(
|
||||
base: NodeJS.ProcessEnv,
|
||||
request: Pick<ExternalToolRunRequest, 'runId' | 'roomId' | 'workspaceId' | 'dance' | 'dataDir'>,
|
||||
workspacePath: string,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): NodeJS.ProcessEnv {
|
||||
return buildExternalProcessEnv(base, {
|
||||
WAGGLE_RUN_ID: request.runId,
|
||||
WAGGLE_ROOM_ID: request.roomId,
|
||||
WAGGLE_WORKSPACE_ID: request.workspaceId,
|
||||
WAGGLE_WORKSPACE_PATH: workspacePath,
|
||||
WAGGLE_SENDER_ID: `run::${request.runId}`,
|
||||
WAGGLE_DANCE_TEAM_ID: `room::${request.roomId}`,
|
||||
...(request.dance ? {
|
||||
WAGGLE_DANCE_URL: request.dance.url,
|
||||
WAGGLE_RUN_TOKEN: request.dance.token,
|
||||
WAGGLE_CLI_NODE_PATH: request.dance.nodePath,
|
||||
WAGGLE_CLI_ENTRY: request.dance.cliEntry,
|
||||
} : {}),
|
||||
...(request.dataDir ? { HIVE_MIND_DATA_DIR: request.dataDir } : {}),
|
||||
WAGGLE_SIGNAL_EMIT: '0',
|
||||
NO_COLOR: '1',
|
||||
}, platform);
|
||||
}
|
||||
|
||||
function requireTaskSpec(
|
||||
manifest: ToolManifest,
|
||||
access: ExternalToolAccess,
|
||||
sessionId?: string,
|
||||
): ToolTaskSpec {
|
||||
if (!manifest.capabilities?.headlessTask || !manifest.task) {
|
||||
throw new Error(`TOOL_NOT_HEADLESS: ${manifest.displayName} can only be opened interactively`);
|
||||
}
|
||||
if (!manifest.task.permissionModes.includes(access)) {
|
||||
throw new Error(`ACCESS_MODE_UNSUPPORTED: ${manifest.displayName} does not support ${access}`);
|
||||
}
|
||||
if (sessionId && (!manifest.task.resumable || !manifest.task.resumeArgvTemplate)) {
|
||||
throw new Error(`RUN_NOT_RESUMABLE: ${manifest.displayName}`);
|
||||
}
|
||||
return manifest.task;
|
||||
}
|
||||
|
||||
function renderArgs(
|
||||
template: readonly string[],
|
||||
task: ToolTaskSpec,
|
||||
request: ExternalToolRunRequest,
|
||||
workspacePath: string,
|
||||
promptFile: string | undefined,
|
||||
timeoutMs: number,
|
||||
): string[] {
|
||||
const values: Record<string, string> = {
|
||||
prompt: request.prompt,
|
||||
workspacePath,
|
||||
workspaceId: request.workspaceId,
|
||||
runId: request.runId,
|
||||
sessionId: request.sessionId ?? '',
|
||||
promptFile: promptFile ?? '',
|
||||
agentId: request.managedAgentId ?? '',
|
||||
timeoutSeconds: String(Math.max(1, Math.ceil(timeoutMs / 1_000))),
|
||||
};
|
||||
const out: string[] = [];
|
||||
for (const part of template) {
|
||||
if (part === '{accessArgs}') {
|
||||
out.push(...(task.accessArgs[request.access] ?? []));
|
||||
continue;
|
||||
}
|
||||
let rendered = part;
|
||||
for (const [name, value] of Object.entries(values)) {
|
||||
rendered = rendered.split(`{${name}}`).join(value);
|
||||
}
|
||||
if (/\{[^{}]+\}/.test(rendered)) throw new Error(`Unresolved adapter placeholder: ${rendered}`);
|
||||
out.push(rendered);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function parseLine(
|
||||
dialect: ToolOutputDialect,
|
||||
line: string,
|
||||
state: ParseState,
|
||||
emit: (type: ExternalRunEventType, text?: string) => void,
|
||||
): void {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) return;
|
||||
if (dialect === 'hermes-text') {
|
||||
const plain = stripAnsi(trimmed).trim();
|
||||
const session = extractSessionId(plain);
|
||||
if (session) state.sessionId = session;
|
||||
else if (hasHermesReasoningStyle(trimmed)) emit('progress', plain);
|
||||
else if (plain) state.finalText = `${state.finalText}${state.finalText ? '\n' : ''}${plain}`;
|
||||
return;
|
||||
}
|
||||
if (dialect === 'text') {
|
||||
const plain = stripAnsi(trimmed).trim();
|
||||
const session = extractSessionId(plain);
|
||||
if (session) state.sessionId = session;
|
||||
else if (plain) state.finalText = `${state.finalText}${state.finalText ? '\n' : ''}${plain}`;
|
||||
return;
|
||||
}
|
||||
let value: unknown;
|
||||
try { value = JSON.parse(trimmed); }
|
||||
catch {
|
||||
if (dialect === 'jsonl' || dialect === 'claude-stream-json' || dialect === 'codex-jsonl') {
|
||||
emit('progress', trimmed);
|
||||
}
|
||||
return;
|
||||
}
|
||||
parseJsonValue(value, dialect, state, emit);
|
||||
}
|
||||
|
||||
function parseWholeJson(
|
||||
text: string,
|
||||
state: ParseState,
|
||||
emit: (type: ExternalRunEventType, text?: string) => void,
|
||||
): void {
|
||||
try { parseJsonValue(JSON.parse(text), 'json', state, emit); }
|
||||
catch { /* the line parser already retained diagnostics */ }
|
||||
}
|
||||
|
||||
function parseJsonValue(
|
||||
value: unknown,
|
||||
dialect: ToolOutputDialect,
|
||||
state: ParseState,
|
||||
emit: (type: ExternalRunEventType, text?: string) => void,
|
||||
): void {
|
||||
if (!value || typeof value !== 'object') return;
|
||||
const record = value as Record<string, unknown>;
|
||||
const type = String(record.type ?? record.event ?? record.status ?? '');
|
||||
const sessionId = stringValue(record.session_id ?? record.sessionId ?? record.thread_id ?? record.threadId);
|
||||
if (sessionId) state.sessionId = sessionId;
|
||||
|
||||
if (dialect === 'claude-stream-json') {
|
||||
if (type === 'result') {
|
||||
const result = stringValue(record.result);
|
||||
const subtype = stringValue(record.subtype);
|
||||
if (result) state.finalText = result;
|
||||
if (record.is_error === true || subtype?.startsWith('error_')) {
|
||||
state.error = stringValue(record.error) || result || subtype || 'Claude Code reported an error';
|
||||
}
|
||||
return;
|
||||
}
|
||||
const blocks = ((record.message as Record<string, unknown> | undefined)?.content ?? record.content) as unknown;
|
||||
const assistantText: string[] = [];
|
||||
for (const block of Array.isArray(blocks) ? blocks : []) {
|
||||
if (!block || typeof block !== 'object') continue;
|
||||
const item = block as Record<string, unknown>;
|
||||
if (item.type === 'text' && typeof item.text === 'string') {
|
||||
assistantText.push(item.text);
|
||||
emit('message', item.text);
|
||||
}
|
||||
if (item.type === 'tool_use') emit('tool', String(item.name ?? 'tool'));
|
||||
}
|
||||
if (assistantText.length > 0) state.finalText = assistantText.join('\n');
|
||||
return;
|
||||
}
|
||||
if (dialect === 'codex-jsonl') {
|
||||
const item = record.item as Record<string, unknown> | undefined;
|
||||
if (type.includes('failed') || type === 'error') state.error = extractText(record) || type;
|
||||
if (item?.type === 'agent_message') {
|
||||
const text = extractText(item);
|
||||
if (text) { state.finalText = text; emit('message', text); }
|
||||
} else if (item?.type) {
|
||||
emit(item.type === 'command_execution' ? 'tool' : 'progress', extractText(item) || String(item.type));
|
||||
}
|
||||
return;
|
||||
}
|
||||
const text = extractText(record);
|
||||
if (text) state.finalText = text;
|
||||
if (type.includes('fail') || type === 'error') state.error = text || type;
|
||||
}
|
||||
|
||||
function extractText(record: Record<string, unknown>): string {
|
||||
for (const key of ['result', 'output', 'text', 'message', 'final', 'response', 'content']) {
|
||||
const value = record[key];
|
||||
if (typeof value === 'string') return value;
|
||||
if (value && typeof value === 'object') {
|
||||
const nested = extractText(value as Record<string, unknown>);
|
||||
if (nested) return nested;
|
||||
}
|
||||
}
|
||||
if (Array.isArray(record.payloads)) {
|
||||
for (const value of record.payloads) {
|
||||
if (value && typeof value === 'object') {
|
||||
const nested = extractText(value as Record<string, unknown>);
|
||||
if (nested) return nested;
|
||||
}
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function stringValue(value: unknown): string | undefined {
|
||||
return typeof value === 'string' && value.length > 0 ? value : undefined;
|
||||
}
|
||||
|
||||
function extractSessionId(value: string): string | undefined {
|
||||
return value.match(/(?:session(?:\s+id)?|session_id)\s*[:=]\s*([\w-]+)/i)?.[1];
|
||||
}
|
||||
|
||||
const ANSI_SGR_PATTERN = new RegExp(String.fromCharCode(27) + '\\[([0-9;]*)m', 'g');
|
||||
|
||||
function hasHermesReasoningStyle(value: string): boolean {
|
||||
ANSI_SGR_PATTERN.lastIndex = 0;
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = ANSI_SGR_PATTERN.exec(value)) !== null) {
|
||||
if (match[1].split(';').some((code) => code === '2' || code === '3')) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function appendTail(current: string, chunk: string, max: number): string {
|
||||
const next = current + chunk;
|
||||
return next.length <= max ? next : next.slice(next.length - max);
|
||||
}
|
||||
|
||||
function truncate(value: string, max: number): string {
|
||||
return value.length <= max ? value : value.slice(0, max);
|
||||
}
|
||||
|
||||
function redact(value: string, env: NodeJS.ProcessEnv): string {
|
||||
let clean = value;
|
||||
for (const [key, secret] of Object.entries(env)) {
|
||||
if (!secret || secret.length < 8 || !/(?:KEY|TOKEN|SECRET)$/i.test(key)) continue;
|
||||
clean = clean.split(secret).join('[REDACTED]');
|
||||
}
|
||||
return clean;
|
||||
}
|
||||
|
||||
function terminalResult(
|
||||
status: ExternalToolRunResult['status'],
|
||||
exitCode: number | null,
|
||||
summary: string,
|
||||
stdoutTail: string,
|
||||
stderrTail: string,
|
||||
durationMs: number,
|
||||
): ExternalToolRunResult {
|
||||
return { status, exitCode, summary, stdoutTail, stderrTail, durationMs };
|
||||
}
|
||||
|
||||
function defaultResolveWorkspacePath(workspacePath: string): string {
|
||||
const resolved = fs.realpathSync(workspacePath);
|
||||
if (!fs.statSync(resolved).isDirectory()) throw new Error(`Workspace path is not a directory: ${workspacePath}`);
|
||||
return resolved;
|
||||
}
|
||||
|
||||
function defaultCreatePromptFile(prompt: string): { path: string; cleanup: () => void } {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-agent-prompt-'));
|
||||
const file = path.join(dir, 'prompt.txt');
|
||||
fs.writeFileSync(file, prompt, { encoding: 'utf8', mode: 0o600 });
|
||||
return { path: file, cleanup: () => fs.rmSync(dir, { recursive: true, force: true }) };
|
||||
}
|
||||
|
||||
function defaultSpawnProcess(
|
||||
binary: string,
|
||||
args: string[],
|
||||
options: { cwd: string; env: NodeJS.ProcessEnv },
|
||||
): ExternalProcessHandle {
|
||||
const invocation = resolveToolCommandInvocation(binary, args);
|
||||
const child = spawnSidecarOwnedProcess(invocation.binary, invocation.args, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
detached: process.platform !== 'win32',
|
||||
windowsHide: true,
|
||||
windowsVerbatimArguments: invocation.windowsVerbatimArguments === true,
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
});
|
||||
return child as unknown as ExternalProcessHandle;
|
||||
}
|
||||
|
||||
export function resolveWindowsTaskkillPath(env: NodeJS.ProcessEnv = process.env): string {
|
||||
const candidate = env.SystemRoot ?? env.WINDIR;
|
||||
const windowsRoot = candidate && path.win32.isAbsolute(candidate)
|
||||
? path.win32.normalize(candidate)
|
||||
: 'C:\\Windows';
|
||||
return path.win32.join(windowsRoot, 'System32', 'taskkill.exe');
|
||||
}
|
||||
|
||||
async function defaultKillTree(pid: number, platform: NodeJS.Platform): Promise<void> {
|
||||
if (platform === 'win32') {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
execFile(
|
||||
resolveWindowsTaskkillPath(),
|
||||
['/PID', String(pid), '/T', '/F'],
|
||||
{ timeout: TREE_KILL_TIMEOUT_MS, windowsHide: true },
|
||||
(error) => error ? reject(error) : resolve(),
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
try { process.kill(-pid, 'SIGTERM'); }
|
||||
catch { try { process.kill(pid, 'SIGTERM'); } catch { /* already gone */ } }
|
||||
}
|
||||
@@ -457,12 +457,10 @@ export {
|
||||
} from './tool-detection.js';
|
||||
export {
|
||||
launchTool,
|
||||
resolveWaggleRuntime,
|
||||
type ToolLauncherDeps,
|
||||
type LaunchOptions,
|
||||
type LaunchResult,
|
||||
type ObservedHandle,
|
||||
type WaggleRuntimePaths,
|
||||
} from './tool-launcher.js';
|
||||
export { spawnSidecarOwnedProcess } from './sidecar-owned-process.js';
|
||||
export {
|
||||
@@ -480,16 +478,6 @@ export { renderGoalAncestry } from './goal-ancestry.js';
|
||||
export { getToolRegistry } from './tool-registry.js';
|
||||
export { loadThirdPartyManifests, type ManifestLoaderDeps } from './tool-manifest-loader.js';
|
||||
export { safeFetch, assertUrlAllowed, allowLocalFromEnv, EgressBlockedError } from './url-egress-guard.js';
|
||||
export {
|
||||
runExternalTool,
|
||||
buildExternalToolEnv,
|
||||
type ExternalRunEvent,
|
||||
type ExternalRunEventType,
|
||||
type ExternalToolRunRequest,
|
||||
type ExternalToolRunResult,
|
||||
type ExternalProcessHandle,
|
||||
type ExternalToolRunnerDeps,
|
||||
} from './external-tool-runner.js';
|
||||
|
||||
// SPEC P1-A — pure ExecutorRouter (A1) + static fit table & task classifier (A2).
|
||||
export {
|
||||
|
||||
@@ -28,9 +28,6 @@
|
||||
*/
|
||||
|
||||
import { spawn, type ChildProcess } from 'node:child_process';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { delimiter, dirname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import type { ToolManifest } from '@waggle/shared';
|
||||
import { BUILTIN_TOOL_MANIFESTS } from '@waggle/shared';
|
||||
import {
|
||||
@@ -348,35 +345,3 @@ export function launchTool(opts: LaunchOptions): LaunchResult {
|
||||
error,
|
||||
};
|
||||
}
|
||||
|
||||
// ── Packaged collaboration CLI ──────────────────────────────────────
|
||||
|
||||
export interface WaggleRuntimePaths {
|
||||
nodePath: string;
|
||||
cliEntry: string;
|
||||
}
|
||||
|
||||
interface RuntimeResolveDeps {
|
||||
nodePath?: string;
|
||||
nodeModulesRoots?: string[];
|
||||
fileExists?: (path: string) => boolean;
|
||||
}
|
||||
|
||||
export function resolveWaggleRuntime(deps: RuntimeResolveDeps = {}): WaggleRuntimePaths | undefined {
|
||||
const fileExists = deps.fileExists ?? existsSync;
|
||||
for (const root of runtimeNodeModulesRoots(deps.nodeModulesRoots)) {
|
||||
const cliEntry = join(root, '@waggle', 'hive-mind-cli', 'dist', 'index.js');
|
||||
if (fileExists(cliEntry)) return { nodePath: deps.nodePath ?? process.execPath, cliEntry };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function runtimeNodeModulesRoots(explicit?: string[]): string[] {
|
||||
const sourceNodeModules = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..', '..', 'node_modules');
|
||||
const roots = explicit ?? [
|
||||
...(process.env.NODE_PATH ?? '').split(delimiter).filter(Boolean),
|
||||
join(process.cwd(), 'node_modules'),
|
||||
sourceNodeModules,
|
||||
];
|
||||
return [...new Set(roots.map((candidate) => resolve(candidate)))];
|
||||
}
|
||||
|
||||
@@ -36,10 +36,18 @@
|
||||
import { execFile } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { resolveWindowsTaskkillPath } from './external-tool-runner.js';
|
||||
|
||||
const WINDOWS_TREE_KILL_TIMEOUT_MS = 5_000;
|
||||
|
||||
/** Absolute path to taskkill.exe, so a PATH entry cannot shadow it. */
|
||||
export function resolveWindowsTaskkillPath(env: NodeJS.ProcessEnv = process.env): string {
|
||||
const candidate = env.SystemRoot ?? env.WINDIR;
|
||||
const windowsRoot = candidate && path.win32.isAbsolute(candidate)
|
||||
? path.win32.normalize(candidate)
|
||||
: 'C:\\Windows';
|
||||
return path.win32.join(windowsRoot, 'System32', 'taskkill.exe');
|
||||
}
|
||||
|
||||
export interface TrackedProcess {
|
||||
pid: number;
|
||||
toolId: string;
|
||||
|
||||
@@ -1,796 +0,0 @@
|
||||
import { EventEmitter } from 'node:events';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { BUILTIN_TOOL_MANIFESTS, type ToolManifest } from '@waggle/shared';
|
||||
import {
|
||||
buildExternalToolEnv,
|
||||
resolveWindowsTaskkillPath,
|
||||
runExternalTool,
|
||||
type ExternalRunEvent,
|
||||
type ExternalProcessHandle,
|
||||
} from '../src/external-tool-runner.js';
|
||||
import { loadThirdPartyManifests } from '../src/tool-manifest-loader.js';
|
||||
|
||||
class FakeStream extends EventEmitter {
|
||||
override on(event: 'data', cb: (chunk: Buffer | string) => void): this {
|
||||
return super.on(event, cb);
|
||||
}
|
||||
}
|
||||
|
||||
class FakeStdin {
|
||||
value = '';
|
||||
ended = false;
|
||||
write(value: string) { this.value += value; }
|
||||
end() { this.ended = true; }
|
||||
}
|
||||
|
||||
class FakeChild extends EventEmitter implements ExternalProcessHandle {
|
||||
pid = 4321;
|
||||
exitCode: number | null = null;
|
||||
signalCode: NodeJS.Signals | null = null;
|
||||
killSignals: Array<NodeJS.Signals | number | undefined> = [];
|
||||
stdout = new FakeStream();
|
||||
stderr = new FakeStream();
|
||||
stdin = new FakeStdin();
|
||||
kill(signal?: NodeJS.Signals | number) {
|
||||
this.killSignals.push(signal);
|
||||
return true;
|
||||
}
|
||||
override once(event: 'error' | 'exit', cb: (...args: never[]) => void): this {
|
||||
return super.once(event, cb);
|
||||
}
|
||||
}
|
||||
|
||||
function manifest(id: string): ToolManifest {
|
||||
const found = BUILTIN_TOOL_MANIFESTS.find((item) => item.id === id);
|
||||
if (!found) throw new Error(`manifest not found: ${id}`);
|
||||
return found;
|
||||
}
|
||||
|
||||
function baseRequest(id: string) {
|
||||
return {
|
||||
manifest: manifest(id),
|
||||
binary: `/bin/${id}`,
|
||||
workspaceId: 'workspace-1',
|
||||
workspacePath: '/workspace',
|
||||
runId: 'run-1',
|
||||
roomId: 'room-1',
|
||||
prompt: 'Review this workspace; do not leak $SECRETS',
|
||||
access: 'read-only' as const,
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('runExternalTool', () => {
|
||||
it('runs Claude Code headlessly with literal stdin and structured result parsing', async () => {
|
||||
const child = new FakeChild();
|
||||
let captured: { args: string[]; env: NodeJS.ProcessEnv } | undefined;
|
||||
const events: string[] = [];
|
||||
const promise = runExternalTool({
|
||||
...baseRequest('claude-code'),
|
||||
onEvent: (event) => events.push(event.type),
|
||||
}, {
|
||||
resolveWorkspacePath: () => '/workspace',
|
||||
baseEnv: { PATH: '/bin', SUPER_SECRET: 'must-not-pass', ANTHROPIC_API_KEY: '12345678-secret' },
|
||||
spawnProcess: (_binary, args, options) => {
|
||||
captured = { args, env: options.env };
|
||||
queueMicrotask(() => {
|
||||
child.stdout.emit('data', '{"type":"system","session_id":"claude-session"}\n');
|
||||
child.stdout.emit('data', '{"type":"assistant","message":{"content":[{"type":"tool_use","name":"Read"}]}}\n');
|
||||
child.stdout.emit('data', '{"type":"result","result":"Claude finished","is_error":false}\n');
|
||||
child.emit('exit', 0);
|
||||
});
|
||||
return child;
|
||||
},
|
||||
});
|
||||
|
||||
const result = await promise;
|
||||
expect(captured?.args).toEqual([
|
||||
'-p', '--safe-mode', '--disable-slash-commands',
|
||||
'--max-budget-usd', '1.00', '--input-format', 'text', '--output-format',
|
||||
'stream-json', '--verbose', '--permission-mode', 'plan',
|
||||
]);
|
||||
expect(captured?.args).not.toContain('--no-session-persistence');
|
||||
expect(child.stdin.value).toBe(baseRequest('claude-code').prompt);
|
||||
expect(result).toMatchObject({ status: 'completed', summary: 'Claude finished', sessionId: 'claude-session' });
|
||||
expect(events).toContain('tool');
|
||||
expect(events.at(-1)).toBe('completed');
|
||||
expect(captured?.env.SUPER_SECRET).toBeUndefined();
|
||||
expect(captured?.env.ANTHROPIC_API_KEY).toBeUndefined();
|
||||
expect(captured?.env.WAGGLE_RUN_ID).toBe('run-1');
|
||||
});
|
||||
|
||||
it('retains Claude assistant text while surfacing a zero-exit budget failure', async () => {
|
||||
const child = new FakeChild();
|
||||
const events: ExternalRunEvent[] = [];
|
||||
const promise = runExternalTool({
|
||||
...baseRequest('claude-code'),
|
||||
onEvent: (event) => events.push(event),
|
||||
}, {
|
||||
resolveWorkspacePath: () => '/workspace',
|
||||
spawnProcess: () => {
|
||||
queueMicrotask(() => {
|
||||
child.stdout.emit('data', '{"type":"system","session_id":"claude-budget-session"}\n');
|
||||
child.stdout.emit('data', '{"type":"assistant","message":{"content":[{"type":"text","text":"OK"}]}}\n');
|
||||
child.stdout.emit('data', '{"type":"result","subtype":"error_max_budget_usd","is_error":false}\n');
|
||||
child.emit('exit', 0);
|
||||
});
|
||||
return child;
|
||||
},
|
||||
});
|
||||
|
||||
const result = await promise;
|
||||
expect(result).toMatchObject({
|
||||
status: 'failed',
|
||||
summary: 'OK',
|
||||
error: 'error_max_budget_usd',
|
||||
sessionId: 'claude-budget-session',
|
||||
});
|
||||
expect(result.summary).not.toContain('"type":"system"');
|
||||
expect(events.at(-1)).toMatchObject({ type: 'failed', text: 'error_max_budget_usd' });
|
||||
});
|
||||
|
||||
it('fails an empty Claude structured result without exposing protocol JSON', async () => {
|
||||
const child = new FakeChild();
|
||||
const promise = runExternalTool(baseRequest('claude-code'), {
|
||||
resolveWorkspacePath: () => '/workspace',
|
||||
spawnProcess: () => {
|
||||
queueMicrotask(() => {
|
||||
child.stdout.emit('data', '{"type":"system","session_id":"empty-session"}\n');
|
||||
child.stdout.emit('data', '{"type":"result","subtype":"success","is_error":false}\n');
|
||||
child.emit('exit', 0);
|
||||
});
|
||||
return child;
|
||||
},
|
||||
});
|
||||
|
||||
const result = await promise;
|
||||
expect(result).toMatchObject({
|
||||
status: 'failed',
|
||||
summary: 'Claude Code completed without a final response',
|
||||
error: 'Claude Code completed without a final response',
|
||||
sessionId: 'empty-session',
|
||||
});
|
||||
expect(result.summary).not.toContain('"type":"system"');
|
||||
expect(result.stdoutTail).toContain('"type":"system"');
|
||||
});
|
||||
|
||||
it('resumes the persisted Claude session without weakening safe mode', async () => {
|
||||
const child = new FakeChild();
|
||||
let args: string[] = [];
|
||||
const promise = runExternalTool({
|
||||
...baseRequest('claude-code'),
|
||||
sessionId: 'claude-session',
|
||||
}, {
|
||||
resolveWorkspacePath: () => '/workspace',
|
||||
spawnProcess: (_binary, value) => {
|
||||
args = value;
|
||||
queueMicrotask(() => {
|
||||
child.stdout.emit('data', '{"type":"result","result":"Resumed","is_error":false}\n');
|
||||
child.emit('exit', 0);
|
||||
});
|
||||
return child;
|
||||
},
|
||||
});
|
||||
|
||||
await expect(promise).resolves.toMatchObject({ status: 'completed', summary: 'Resumed' });
|
||||
expect(args).toEqual([
|
||||
'-p', '--safe-mode', '--disable-slash-commands', '--resume', 'claude-session',
|
||||
'--max-budget-usd', '1.00', '--input-format', 'text', '--output-format',
|
||||
'stream-json', '--verbose', '--permission-mode', 'plan',
|
||||
]);
|
||||
});
|
||||
|
||||
it('runs Codex through exec with an explicit workspace sandbox', async () => {
|
||||
const child = new FakeChild();
|
||||
let args: string[] = [];
|
||||
const promise = runExternalTool({
|
||||
...baseRequest('codex'),
|
||||
access: 'workspace-write',
|
||||
}, {
|
||||
resolveWorkspacePath: () => 'C:\\workspace',
|
||||
spawnProcess: (_binary, value) => {
|
||||
args = value;
|
||||
queueMicrotask(() => {
|
||||
child.stdout.emit('data', '{"type":"thread.started","thread_id":"codex-session"}\n');
|
||||
child.stdout.emit('data', '{"type":"item.completed","item":{"type":"agent_message","text":"Codex finished"}}\n');
|
||||
child.emit('exit', 0);
|
||||
});
|
||||
return child;
|
||||
},
|
||||
});
|
||||
const result = await promise;
|
||||
expect(args).toEqual([
|
||||
'--ask-for-approval', 'never', '--sandbox', 'workspace-write', 'exec',
|
||||
'--ignore-user-config', '--ignore-rules', '--skip-git-repo-check',
|
||||
'--json', '--color', 'never', '-C', 'C:\\workspace', '-',
|
||||
]);
|
||||
expect(args).not.toContain('--ephemeral');
|
||||
expect(child.stdin.value).toBe(baseRequest('codex').prompt);
|
||||
expect(result).toMatchObject({ status: 'completed', summary: 'Codex finished', sessionId: 'codex-session' });
|
||||
});
|
||||
|
||||
it('resumes Codex with exec-level flags before the resume subcommand', async () => {
|
||||
const child = new FakeChild();
|
||||
let args: string[] = [];
|
||||
const promise = runExternalTool({
|
||||
...baseRequest('codex'),
|
||||
sessionId: '00000000-0000-0000-0000-000000000000',
|
||||
}, {
|
||||
resolveWorkspacePath: () => 'C:\\workspace',
|
||||
spawnProcess: (_binary, value) => {
|
||||
args = value;
|
||||
queueMicrotask(() => {
|
||||
child.stdout.emit('data', '{"type":"item.completed","item":{"type":"agent_message","text":"Codex resumed"}}\n');
|
||||
child.emit('exit', 0);
|
||||
});
|
||||
return child;
|
||||
},
|
||||
});
|
||||
|
||||
await expect(promise).resolves.toMatchObject({ status: 'completed', summary: 'Codex resumed' });
|
||||
expect(args).toEqual([
|
||||
'--ask-for-approval', 'never', '--sandbox', 'read-only', 'exec',
|
||||
'--ignore-user-config', '--ignore-rules', '--skip-git-repo-check',
|
||||
'--color', 'never', '-C', 'C:\\workspace', 'resume', '--json',
|
||||
'00000000-0000-0000-0000-000000000000', '-',
|
||||
]);
|
||||
expect(args).not.toContain('--ephemeral');
|
||||
});
|
||||
|
||||
it('uses Hermes quiet query mode without unsafe yolo/oneshot flags', async () => {
|
||||
const child = new FakeChild();
|
||||
let args: string[] = [];
|
||||
const prompt = baseRequest('hermes').prompt;
|
||||
const promise = runExternalTool({ ...baseRequest('hermes'), access: 'native' }, {
|
||||
resolveWorkspacePath: () => '/workspace',
|
||||
spawnProcess: (_binary, value) => {
|
||||
args = value;
|
||||
queueMicrotask(() => {
|
||||
child.stdout.emit('data', 'Hermes finished\nSession ID: hermes-session\n');
|
||||
child.emit('exit', 0);
|
||||
});
|
||||
return child;
|
||||
},
|
||||
});
|
||||
const result = await promise;
|
||||
expect(args).toEqual([
|
||||
'chat', '-q', prompt, '-Q', '--source', 'tool', '--ignore-rules',
|
||||
'--max-turns', '12', '--checkpoints',
|
||||
]);
|
||||
expect(args).not.toContain('--yolo');
|
||||
expect(args).not.toContain('--oneshot');
|
||||
expect(child.stdin.value).toBe('');
|
||||
expect(result).toMatchObject({ status: 'completed', summary: 'Hermes finished', sessionId: 'hermes-session' });
|
||||
});
|
||||
|
||||
it.runIf(process.platform === 'win32')('fails closed before a Hermes batch shim can reparse its prompt', async () => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-hermes-unsafe-batch-'));
|
||||
const batch = path.join(directory, 'hermes.cmd');
|
||||
const marker = path.join(directory, 'injected.txt');
|
||||
fs.writeFileSync(batch, '@echo off\r\necho Hermes finished\r\n');
|
||||
|
||||
try {
|
||||
const result = await runExternalTool({
|
||||
...baseRequest('hermes'),
|
||||
binary: batch,
|
||||
workspacePath: directory,
|
||||
prompt: `safe" & echo injected>${marker} & rem`,
|
||||
access: 'native',
|
||||
}, { platform: 'win32' });
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: 'failed',
|
||||
summary: expect.stringContaining('UNSAFE_WINDOWS_BATCH_SHIM'),
|
||||
});
|
||||
expect(fs.existsSync(marker)).toBe(false);
|
||||
} finally {
|
||||
fs.rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps resumed Hermes sessions in the newly assigned workspace', async () => {
|
||||
const child = new FakeChild();
|
||||
let args: string[] = [];
|
||||
let cwd = '';
|
||||
const prompt = baseRequest('hermes').prompt;
|
||||
const promise = runExternalTool({
|
||||
...baseRequest('hermes'),
|
||||
access: 'native',
|
||||
sessionId: '20260801_resume',
|
||||
}, {
|
||||
resolveWorkspacePath: () => 'C:\\assigned-workspace',
|
||||
spawnProcess: (_binary, value, options) => {
|
||||
args = value;
|
||||
cwd = options.cwd;
|
||||
queueMicrotask(() => {
|
||||
child.stdout.emit('data', 'Hermes resumed\n');
|
||||
child.emit('exit', 0);
|
||||
});
|
||||
return child;
|
||||
},
|
||||
});
|
||||
|
||||
await expect(promise).resolves.toMatchObject({ status: 'completed', summary: 'Hermes resumed' });
|
||||
expect(cwd).toBe('C:\\assigned-workspace');
|
||||
expect(args).toEqual([
|
||||
'chat', '--resume', '20260801_resume', '--no-restore-cwd', '-q', prompt,
|
||||
'-Q', '--source', 'tool', '--ignore-rules', '--max-turns', '12', '--checkpoints',
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps Hermes reasoning as progress and parses its stderr session trailer', async () => {
|
||||
const child = new FakeChild();
|
||||
const events: Array<{ type: string; text?: string }> = [];
|
||||
const promise = runExternalTool({
|
||||
...baseRequest('hermes'),
|
||||
access: 'native',
|
||||
onEvent: (event) => events.push({ type: event.type, text: event.text }),
|
||||
}, {
|
||||
platform: 'win32',
|
||||
resolveWorkspacePath: () => 'C:\\workspace',
|
||||
spawnProcess: () => {
|
||||
queueMicrotask(() => {
|
||||
child.stdout.emit('data', '\u001b[2;3mInspecting the workspace first.\u001b[0m\r\n');
|
||||
child.stdout.emit('data', '\u001b[2;3mChecking the relevant tests.\u001b[0m\r\n');
|
||||
child.stdout.emit('data', 'Hermes completed the requested review.\r\n');
|
||||
child.stderr.emit('data', 'Warning: terminal capability fallback\r\n\rsession_');
|
||||
child.stderr.emit('data', 'id: 20260711_hermes123\r\n');
|
||||
child.emit('exit', 0);
|
||||
});
|
||||
return child;
|
||||
},
|
||||
});
|
||||
|
||||
const result = await promise;
|
||||
expect(result).toMatchObject({
|
||||
status: 'completed',
|
||||
summary: 'Hermes completed the requested review.',
|
||||
sessionId: '20260711_hermes123',
|
||||
});
|
||||
expect(result.summary).not.toContain('\u001b');
|
||||
expect(result.stderrTail).toContain('terminal capability fallback');
|
||||
expect(events).toContainEqual({ type: 'progress', text: 'Inspecting the workspace first.' });
|
||||
expect(events).toContainEqual({ type: 'progress', text: 'Checking the relevant tests.' });
|
||||
expect(events.at(-1)).toEqual({ type: 'completed', text: result.summary });
|
||||
});
|
||||
|
||||
it('binds OpenClaw to a managed workspace agent and deletes its prompt file', async () => {
|
||||
const child = new FakeChild();
|
||||
let args: string[] = [];
|
||||
let promptFileContent = '';
|
||||
let cleaned = false;
|
||||
const promise = runExternalTool({
|
||||
...baseRequest('openclaw'),
|
||||
access: 'native',
|
||||
managedAgentId: 'waggle-workspace-1',
|
||||
}, {
|
||||
resolveWorkspacePath: () => '/workspace',
|
||||
createPromptFile: (prompt) => {
|
||||
promptFileContent = prompt;
|
||||
return { path: '/tmp/prompt.txt', cleanup: () => { cleaned = true; } };
|
||||
},
|
||||
spawnProcess: (_binary, value) => {
|
||||
args = value;
|
||||
queueMicrotask(() => {
|
||||
child.stdout.emit('data', JSON.stringify({
|
||||
status: 'ok', sessionId: 'openclaw-session', result: { payloads: [{ text: 'OpenClaw finished' }] },
|
||||
}));
|
||||
child.emit('exit', 0);
|
||||
});
|
||||
return child;
|
||||
},
|
||||
});
|
||||
const result = await promise;
|
||||
expect(args).toEqual([
|
||||
'agent', '--agent', 'waggle-workspace-1', '--session-key',
|
||||
'agent:waggle-workspace-1:waggle:run-1', '--message-file', '/tmp/prompt.txt',
|
||||
'--json', '--timeout', '600',
|
||||
]);
|
||||
expect(promptFileContent).toBe(baseRequest('openclaw').prompt);
|
||||
expect(cleaned).toBe(true);
|
||||
expect(result).toMatchObject({ status: 'completed', summary: 'OpenClaw finished', sessionId: 'openclaw-session' });
|
||||
});
|
||||
|
||||
it('rejects GUI-only tools instead of pretending that launch equals task execution', async () => {
|
||||
await expect(runExternalTool(baseRequest('cursor'), {
|
||||
resolveWorkspacePath: () => '/workspace',
|
||||
spawnProcess: () => { throw new Error('must not spawn'); },
|
||||
})).rejects.toThrow(/TOOL_NOT_HEADLESS/);
|
||||
});
|
||||
|
||||
it('redacts the narrow collaboration credential from structured output', async () => {
|
||||
const child = new FakeChild();
|
||||
const token = 'run-token-that-must-never-be-persisted-12345';
|
||||
const promise = runExternalTool({
|
||||
...baseRequest('claude-code'),
|
||||
dance: {
|
||||
url: 'http://127.0.0.1:3333', token,
|
||||
nodePath: '/runtime/node', cliEntry: '/runtime/hive-mind-cli.js',
|
||||
},
|
||||
dataDir: '/waggle-data',
|
||||
}, {
|
||||
resolveWorkspacePath: () => '/workspace',
|
||||
spawnProcess: () => {
|
||||
queueMicrotask(() => {
|
||||
child.stdout.emit('data', `{"type":"result","result":"accidental ${token}","is_error":false}\n`);
|
||||
child.emit('exit', 0);
|
||||
});
|
||||
return child;
|
||||
},
|
||||
});
|
||||
|
||||
const result = await promise;
|
||||
expect(result.summary).toContain('[REDACTED]');
|
||||
expect(result.summary).not.toContain(token);
|
||||
expect(result.stdoutTail).not.toContain(token);
|
||||
});
|
||||
|
||||
it('cancels one process tree exactly once', async () => {
|
||||
const child = new FakeChild();
|
||||
const controller = new AbortController();
|
||||
let kills = 0;
|
||||
const promise = runExternalTool({ ...baseRequest('claude-code'), signal: controller.signal }, {
|
||||
resolveWorkspacePath: () => '/workspace',
|
||||
spawnProcess: () => {
|
||||
queueMicrotask(() => {
|
||||
controller.abort();
|
||||
setTimeout(() => child.emit('exit', null), 0);
|
||||
});
|
||||
return child;
|
||||
},
|
||||
killTree: async () => { kills++; },
|
||||
});
|
||||
const result = await promise;
|
||||
expect(kills).toBe(1);
|
||||
expect(result.status).toBe('cancelled');
|
||||
});
|
||||
|
||||
it('does not kill a process that exited before a queued abort is handled', async () => {
|
||||
const child = new FakeChild();
|
||||
const controller = new AbortController();
|
||||
let treeKills = 0;
|
||||
const promise = runExternalTool({
|
||||
...baseRequest('hermes'),
|
||||
access: 'native',
|
||||
signal: controller.signal,
|
||||
}, {
|
||||
resolveWorkspacePath: () => '/workspace',
|
||||
spawnProcess: () => {
|
||||
queueMicrotask(() => {
|
||||
child.exitCode = 0;
|
||||
controller.abort();
|
||||
});
|
||||
return child;
|
||||
},
|
||||
killTree: async () => { treeKills += 1; },
|
||||
});
|
||||
|
||||
await expect(promise).resolves.toMatchObject({ status: 'completed', exitCode: 0 });
|
||||
expect(treeKills).toBe(0);
|
||||
expect(child.killSignals).toEqual([]);
|
||||
});
|
||||
|
||||
it('recovers a spawn/listener abort race when tree cleanup rejects', async () => {
|
||||
vi.useFakeTimers();
|
||||
const child = new FakeChild();
|
||||
const controller = new AbortController();
|
||||
const cleanup = vi.fn();
|
||||
const events: ExternalRunEvent[] = [];
|
||||
const promise = runExternalTool({
|
||||
...baseRequest('openclaw'),
|
||||
access: 'native',
|
||||
managedAgentId: 'waggle-workspace-1',
|
||||
signal: controller.signal,
|
||||
onEvent: (event) => events.push(event),
|
||||
}, {
|
||||
resolveWorkspacePath: () => '/workspace',
|
||||
createPromptFile: () => ({ path: '/tmp/prompt.txt', cleanup }),
|
||||
spawnProcess: () => {
|
||||
controller.abort();
|
||||
return child;
|
||||
},
|
||||
killTree: async () => { throw new Error('tree cleanup failed'); },
|
||||
});
|
||||
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(child.killSignals).toEqual(['SIGKILL']);
|
||||
let settled = false;
|
||||
void promise.then(() => { settled = true; });
|
||||
await vi.advanceTimersByTimeAsync(1_999);
|
||||
expect(settled).toBe(false);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
|
||||
await expect(promise).resolves.toMatchObject({
|
||||
status: 'cancelled',
|
||||
stderrTail: expect.stringContaining('tree cleanup failed'),
|
||||
});
|
||||
expect(cleanup).toHaveBeenCalledTimes(1);
|
||||
expect(events.filter((event) => event.type === 'cancelled')).toHaveLength(1);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('bounds a hung tree cleanup and a child that never exits', async () => {
|
||||
vi.useFakeTimers();
|
||||
const child = new FakeChild();
|
||||
const controller = new AbortController();
|
||||
let treeKills = 0;
|
||||
const promise = runExternalTool({
|
||||
...baseRequest('claude-code'),
|
||||
timeoutMs: 120_000,
|
||||
signal: controller.signal,
|
||||
}, {
|
||||
resolveWorkspacePath: () => '/workspace',
|
||||
spawnProcess: () => child,
|
||||
killTree: () => {
|
||||
treeKills += 1;
|
||||
return new Promise<void>(() => {});
|
||||
},
|
||||
});
|
||||
controller.abort();
|
||||
|
||||
let settled = false;
|
||||
void promise.then(() => { settled = true; });
|
||||
await vi.advanceTimersByTimeAsync(4_999);
|
||||
expect(settled).toBe(false);
|
||||
expect(child.killSignals).toEqual([]);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(treeKills).toBe(1);
|
||||
expect(child.killSignals).toEqual(['SIGKILL']);
|
||||
await vi.advanceTimersByTimeAsync(1_999);
|
||||
expect(settled).toBe(false);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
|
||||
await expect(promise).resolves.toMatchObject({ status: 'cancelled' });
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('preserves a timeout that wins before a later abort', async () => {
|
||||
vi.useFakeTimers();
|
||||
const child = new FakeChild();
|
||||
const controller = new AbortController();
|
||||
let treeKills = 0;
|
||||
const promise = runExternalTool({
|
||||
...baseRequest('codex'),
|
||||
timeoutMs: 1_000,
|
||||
signal: controller.signal,
|
||||
}, {
|
||||
resolveWorkspacePath: () => '/workspace',
|
||||
spawnProcess: () => child,
|
||||
killTree: async () => { treeKills += 1; },
|
||||
});
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1_000);
|
||||
controller.abort();
|
||||
await vi.advanceTimersByTimeAsync(2_000);
|
||||
|
||||
await expect(promise).resolves.toMatchObject({ status: 'timed_out' });
|
||||
expect(treeKills).toBe(1);
|
||||
expect(child.killSignals).toEqual([]);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('emits one stall per quiet episode, recovers on output, and clears its watchdog on exit', async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(0);
|
||||
const child = new FakeChild();
|
||||
const events: ExternalRunEvent[] = [];
|
||||
const promise = runExternalTool({
|
||||
...baseRequest('claude-code'),
|
||||
timeoutMs: 120_000,
|
||||
stallAfterMs: 30_000,
|
||||
onEvent: (event) => events.push(event),
|
||||
}, {
|
||||
resolveWorkspacePath: () => '/workspace',
|
||||
spawnProcess: () => child,
|
||||
});
|
||||
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(events.filter((event) => event.stalled === true)).toHaveLength(1);
|
||||
expect(events).toContainEqual(expect.objectContaining({
|
||||
type: 'progress',
|
||||
text: '[stalled] no output for 30s',
|
||||
stalled: true,
|
||||
}));
|
||||
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(events.filter((event) => event.stalled === true)).toHaveLength(1);
|
||||
|
||||
child.stdout.emit('data', '{"type":"system"}\n');
|
||||
expect(events).toContainEqual(expect.objectContaining({
|
||||
type: 'progress',
|
||||
text: '[recovered] output resumed',
|
||||
stalled: false,
|
||||
}));
|
||||
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(events.filter((event) => event.stalled === true)).toHaveLength(2);
|
||||
|
||||
child.emit('exit', 0);
|
||||
await promise;
|
||||
const eventCountAtExit = events.length;
|
||||
await vi.advanceTimersByTimeAsync(300_000);
|
||||
expect(events).toHaveLength(eventCountAtExit);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('does not emit a stall after cancellation while process exit is pending', async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(0);
|
||||
const child = new FakeChild();
|
||||
const controller = new AbortController();
|
||||
const events: ExternalRunEvent[] = [];
|
||||
const promise = runExternalTool({
|
||||
...baseRequest('claude-code'),
|
||||
timeoutMs: 120_000,
|
||||
stallAfterMs: 30_000,
|
||||
signal: controller.signal,
|
||||
onEvent: (event) => events.push(event),
|
||||
}, {
|
||||
resolveWorkspacePath: () => '/workspace',
|
||||
spawnProcess: () => child,
|
||||
killTree: async () => undefined,
|
||||
});
|
||||
|
||||
await vi.advanceTimersByTimeAsync(10_000);
|
||||
controller.abort();
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
expect(events.some((event) => event.stalled === true)).toBe(false);
|
||||
|
||||
child.emit('exit', null);
|
||||
await expect(promise).resolves.toMatchObject({ status: 'cancelled' });
|
||||
});
|
||||
|
||||
it.each([
|
||||
['uses the default', undefined, 120_000],
|
||||
['respects an override', 45_000, 45_000],
|
||||
['clamps short overrides', 1_000, 30_000],
|
||||
])('%s stall delay', async (_label, configuredStallAfterMs, expectedStallAfterMs) => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(0);
|
||||
const child = new FakeChild();
|
||||
const events: ExternalRunEvent[] = [];
|
||||
const promise = runExternalTool({
|
||||
...baseRequest('claude-code'),
|
||||
timeoutMs: 300_000,
|
||||
...(configuredStallAfterMs === undefined ? {} : { stallAfterMs: configuredStallAfterMs }),
|
||||
onEvent: (event) => events.push(event),
|
||||
}, {
|
||||
resolveWorkspacePath: () => '/workspace',
|
||||
spawnProcess: () => child,
|
||||
});
|
||||
|
||||
await vi.advanceTimersByTimeAsync(expectedStallAfterMs - 1);
|
||||
expect(events.some((event) => event.stalled === true)).toBe(false);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(events.filter((event) => event.stalled === true)).toHaveLength(1);
|
||||
|
||||
child.emit('exit', 0);
|
||||
await promise;
|
||||
});
|
||||
|
||||
it('disables the stall watchdog when its threshold is not below the run timeout', async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(0);
|
||||
const child = new FakeChild();
|
||||
const events: ExternalRunEvent[] = [];
|
||||
const promise = runExternalTool({
|
||||
...baseRequest('claude-code'),
|
||||
timeoutMs: 30_000,
|
||||
stallAfterMs: 30_000,
|
||||
onEvent: (event) => events.push(event),
|
||||
}, {
|
||||
resolveWorkspacePath: () => '/workspace',
|
||||
spawnProcess: () => child,
|
||||
killTree: async () => undefined,
|
||||
});
|
||||
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(events.some((event) => event.stalled !== undefined)).toBe(false);
|
||||
child.emit('exit', null);
|
||||
await expect(promise).resolves.toMatchObject({ status: 'timed_out' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('external adapter safety', () => {
|
||||
it('resolves taskkill from an absolute Windows system directory', () => {
|
||||
expect(resolveWindowsTaskkillPath({ SystemRoot: 'C:\\Windows' }))
|
||||
.toBe('C:\\Windows\\System32\\taskkill.exe');
|
||||
expect(resolveWindowsTaskkillPath({ WINDIR: 'D:\\WinNT' }))
|
||||
.toBe('D:\\WinNT\\System32\\taskkill.exe');
|
||||
expect(resolveWindowsTaskkillPath({ SystemRoot: 'relative\\windows' }))
|
||||
.toBe('C:\\Windows\\System32\\taskkill.exe');
|
||||
});
|
||||
|
||||
it('passes OS context and explicit run identity but no ambient secrets', () => {
|
||||
const env = buildExternalToolEnv(
|
||||
{
|
||||
PATH: 'C:\\Windows\\System32', USERPROFILE: 'C:\\Users\\tester',
|
||||
APPDATA: 'C:\\Users\\tester\\AppData\\Roaming',
|
||||
LOCALAPPDATA: 'C:\\Redirected\\Local', HERMES_HOME: 'D:\\Hermes Data',
|
||||
TERM: 'xterm-256color',
|
||||
ANTHROPIC_API_KEY: 'anthropic-secret', OPENAI_API_KEY: 'openai-secret',
|
||||
OPENROUTER_API_KEY: 'openrouter-secret', GOOGLE_API_KEY: 'google-secret',
|
||||
GEMINI_API_KEY: 'gemini-secret', XAI_API_KEY: 'xai-secret',
|
||||
STRIPE_SECRET_KEY: 'stripe-secret', AWS_SECRET_ACCESS_KEY: 'aws-secret',
|
||||
DATABASE_URL: 'database-secret', SSH_AUTH_SOCK: 'credential-socket',
|
||||
GIT_ASKPASS: 'credential-helper', HTTPS_PROXY: 'https://user:secret@proxy.invalid',
|
||||
NODE_OPTIONS: '--require C:\\malicious.js', WAGGLE_RUN_TOKEN: 'stale-token',
|
||||
},
|
||||
{
|
||||
runId: 'run', roomId: 'room', workspaceId: 'workspace',
|
||||
dance: {
|
||||
url: 'http://127.0.0.1:3333', token: 'run-token-123456789012345678901234',
|
||||
nodePath: '/runtime/node', cliEntry: '/runtime/hive-mind-cli.js',
|
||||
},
|
||||
dataDir: '/waggle-data',
|
||||
},
|
||||
'/workspace',
|
||||
'win32',
|
||||
);
|
||||
expect(env).toMatchObject({
|
||||
PATH: 'C:\\Windows\\System32',
|
||||
USERPROFILE: 'C:\\Users\\tester',
|
||||
APPDATA: 'C:\\Users\\tester\\AppData\\Roaming',
|
||||
LOCALAPPDATA: 'C:\\Redirected\\Local',
|
||||
HERMES_HOME: 'D:\\Hermes Data',
|
||||
TERM: 'xterm-256color',
|
||||
});
|
||||
for (const name of [
|
||||
'ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'OPENROUTER_API_KEY',
|
||||
'GOOGLE_API_KEY', 'GEMINI_API_KEY', 'XAI_API_KEY',
|
||||
'STRIPE_SECRET_KEY', 'AWS_SECRET_ACCESS_KEY', 'DATABASE_URL',
|
||||
'SSH_AUTH_SOCK', 'GIT_ASKPASS', 'HTTPS_PROXY', 'NODE_OPTIONS',
|
||||
]) {
|
||||
expect(env[name], name).toBeUndefined();
|
||||
}
|
||||
expect(env.WAGGLE_DANCE_TEAM_ID).toBe('room::room');
|
||||
expect(env.WAGGLE_DANCE_URL).toBe('http://127.0.0.1:3333');
|
||||
expect(env.WAGGLE_RUN_TOKEN).toBe('run-token-123456789012345678901234');
|
||||
expect(env.WAGGLE_CLI_NODE_PATH).toBe('/runtime/node');
|
||||
expect(env.WAGGLE_CLI_ENTRY).toBe('/runtime/hive-mind-cli.js');
|
||||
expect(env.HIVE_MIND_DATA_DIR).toBe('/waggle-data');
|
||||
|
||||
const withoutDance = buildExternalToolEnv(
|
||||
{ WAGGLE_RUN_TOKEN: 'stale-ambient-token' },
|
||||
{ runId: 'run', roomId: 'room', workspaceId: 'workspace' },
|
||||
'/workspace',
|
||||
'win32',
|
||||
);
|
||||
expect(withoutDance.WAGGLE_RUN_TOKEN).toBeUndefined();
|
||||
});
|
||||
|
||||
it('loads only data-only generic task specs with known placeholders', () => {
|
||||
const base = {
|
||||
id: 'safe-cli', displayName: 'Safe', launchable: true,
|
||||
detect: { kind: 'path', binaryName: 'safe' },
|
||||
};
|
||||
const deps = (value: unknown) => ({
|
||||
dir: '/fake', readDir: () => ['adapter.json'], readFile: () => JSON.stringify(value),
|
||||
});
|
||||
const safe = loadThirdPartyManifests(deps({
|
||||
...base,
|
||||
task: {
|
||||
argvTemplate: ['run', '--workspace', '{workspacePath}', '{prompt}'],
|
||||
accessArgs: { 'read-only': [] }, promptTransport: 'arg', outputDialect: 'jsonl',
|
||||
workspaceBinding: 'flag', permissionModes: ['read-only'], resumable: false,
|
||||
},
|
||||
}));
|
||||
expect(safe[0]?.capabilities?.headlessTask).toBe(true);
|
||||
|
||||
expect(loadThirdPartyManifests(deps({
|
||||
...base,
|
||||
task: {
|
||||
argvTemplate: ['run', '{executeJavascript}'], accessArgs: { native: [] },
|
||||
promptTransport: 'stdin', outputDialect: 'jsonl', workspaceBinding: 'cwd',
|
||||
permissionModes: ['native'], resumable: false,
|
||||
},
|
||||
}))).toEqual([]);
|
||||
expect(loadThirdPartyManifests(deps({ ...base, parserModule: './evil.js' }))).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -8,13 +8,12 @@
|
||||
import { execFileSync, type ChildProcess } from 'node:child_process';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { join } from 'node:path';
|
||||
import {
|
||||
launchTool,
|
||||
createObservedHandle,
|
||||
defaultSpawnObserved,
|
||||
resolveSpawnInvocation,
|
||||
resolveWaggleRuntime,
|
||||
type ToolLauncherDeps,
|
||||
type ObservedHandle,
|
||||
} from '../src/tool-launcher.js';
|
||||
@@ -404,23 +403,6 @@ describe('launchTool observe mode', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveWaggleRuntime', () => {
|
||||
it('resolves the collaboration CLI from an explicit staged node_modules root', () => {
|
||||
const root = join('resources', 'node_modules');
|
||||
const cliEntry = join(root, '@waggle', 'hive-mind-cli', 'dist', 'index.js');
|
||||
const runtime = resolveWaggleRuntime({
|
||||
nodePath: join('resources', 'node'),
|
||||
nodeModulesRoots: [root],
|
||||
fileExists: (candidate) => candidate === resolve(cliEntry),
|
||||
});
|
||||
expect(runtime).toEqual({ nodePath: join('resources', 'node'), cliEntry: resolve(cliEntry) });
|
||||
});
|
||||
|
||||
it('fails closed when the collaboration CLI is not staged', () => {
|
||||
expect(resolveWaggleRuntime({ nodeModulesRoots: ['/missing'], fileExists: () => false })).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('launchTool collaboration env', () => {
|
||||
it('injects the canonical Waggle data root', () => {
|
||||
const { calls, spawnDetached } = captureSpawn();
|
||||
|
||||
@@ -10,8 +10,11 @@ import { execFileSync, spawn } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { resolveWindowsTaskkillPath } from '../src/external-tool-runner.js';
|
||||
import { ToolProcessTracker, type TrackedProcess } from '../src/tool-process-tracker.js';
|
||||
import {
|
||||
ToolProcessTracker,
|
||||
resolveWindowsTaskkillPath,
|
||||
type TrackedProcess,
|
||||
} from '../src/tool-process-tracker.js';
|
||||
|
||||
describe('ToolProcessTracker', () => {
|
||||
it('registers a pid and reports it', () => {
|
||||
|
||||
@@ -93,7 +93,6 @@ import { anthropicProxyRoutes } from './routes/anthropic-proxy.js';
|
||||
import { taskRoutes } from './routes/tasks.js';
|
||||
import { capabilitiesRoutes } from './routes/capabilities.js';
|
||||
import { toolsRoutes } from './routes/tools.js';
|
||||
import { externalToolRunRoutes } from './routes/external-tool-runs.js';
|
||||
import { routeProposalRoutes } from './routes/route-proposals.js';
|
||||
import { SignalBus } from './signal-bus.js';
|
||||
import { commandRoutes } from './routes/commands.js';
|
||||
@@ -1950,7 +1949,6 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
|
||||
await server.register(taskRoutes);
|
||||
await server.register(capabilitiesRoutes);
|
||||
await server.register(toolsRoutes);
|
||||
await server.register(externalToolRunRoutes);
|
||||
await server.register(routeProposalRoutes);
|
||||
server.decorate('signalBus', new SignalBus());
|
||||
await server.register(commandRoutes);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -529,10 +529,6 @@ function mutationWorkspaceIds(
|
||||
return fallbackWorkspaceId ? [fallbackWorkspaceId] : [];
|
||||
}
|
||||
|
||||
const participantWorkspaceIds = Array.isArray(body?.participants)
|
||||
? body.participants.flatMap((participant) =>
|
||||
stringArrayFields(asRecord(participant), ['workspaceIds']))
|
||||
: [];
|
||||
const bodyWorkspaceIds = stringFields(body, ['workspaceId', 'workspace', 'parentWorkspaceId']);
|
||||
const directBodyWorkspaceIds = request.method === 'POST'
|
||||
&& (routeUrl === '/api/cron' || routeUrl === '/api/automations')
|
||||
@@ -543,7 +539,6 @@ function mutationWorkspaceIds(
|
||||
...directBodyWorkspaceIds,
|
||||
...stringFields(query, ['workspaceId', 'workspace']),
|
||||
...stringArrayFields(body, ['workspaceIds']),
|
||||
...participantWorkspaceIds,
|
||||
...storedMutationWorkspaceIds(request, fastify, routeUrl),
|
||||
...createdCronWorkspaceIds(body, fastify, routeUrl),
|
||||
])];
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import Fastify from 'fastify';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { AgentRunRegistry } from '../../src/local/agent-run-registry.js';
|
||||
import { externalToolRunRoutes } from '../../src/local/routes/external-tool-runs.js';
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
for (const dir of tempDirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('external tool roadmap gate', () => {
|
||||
it('rejects OpenClaw before workspace, run, or process side effects', async () => {
|
||||
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-roadmap-tool-'));
|
||||
tempDirs.push(dataDir);
|
||||
const registry = new AgentRunRegistry(path.join(dataDir, 'agent-runs.json'));
|
||||
const workspaceLookup = vi.fn();
|
||||
const runner = vi.fn();
|
||||
const server = Fastify({ logger: false });
|
||||
server.decorate('agentRunRegistry', registry);
|
||||
server.decorate('workspaceManager', { get: workspaceLookup } as never);
|
||||
server.decorate('externalToolDetector', async () => ({
|
||||
platform: 'win32',
|
||||
detectedAt: new Date().toISOString(),
|
||||
tools: [{
|
||||
id: 'openclaw',
|
||||
displayName: 'OpenClaw',
|
||||
releaseStatus: 'supported',
|
||||
launchable: true,
|
||||
installed: true,
|
||||
installedPath: 'C:\\tools\\openclaw.cmd',
|
||||
version: 'test',
|
||||
}],
|
||||
}));
|
||||
server.decorate('externalToolRunner', runner);
|
||||
await server.register(externalToolRunRoutes);
|
||||
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/tools/run',
|
||||
payload: { toolId: 'openclaw', workspaceIds: ['alpha'], prompt: 'Do work' },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(409);
|
||||
expect(response.json()).toMatchObject({
|
||||
error: 'tool_not_release_supported',
|
||||
toolId: 'openclaw',
|
||||
});
|
||||
expect(workspaceLookup).not.toHaveBeenCalled();
|
||||
expect(runner).not.toHaveBeenCalled();
|
||||
expect(registry.snapshot().runs).toHaveLength(0);
|
||||
await server.close();
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -819,7 +819,6 @@ describe('Team viewer read-only enforcement', () => {
|
||||
server.post('/api/agent-groups/:id/run', mutate);
|
||||
server.post('/api/tools/launch', mutate);
|
||||
server.post('/api/chat', mutate);
|
||||
server.post('/api/tools/run', mutate);
|
||||
server.post('/api/rooms', mutate);
|
||||
server.post('/api/cron', mutate);
|
||||
server.patch('/api/cron/:id', mutate);
|
||||
@@ -1122,19 +1121,6 @@ describe('Team viewer read-only enforcement', () => {
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
label: 'nested participant workspaceIds array',
|
||||
request: {
|
||||
method: 'POST' as const,
|
||||
url: '/api/tools/run',
|
||||
payload: {
|
||||
participants: [
|
||||
{ toolId: 'codex', workspaceIds: ['member-workspace'] },
|
||||
{ toolId: 'claude-code', workspaceIds: ['viewer-workspace'] },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
])('rejects viewer mutation resolved from $label before the handler runs', async ({ request }) => {
|
||||
const { server, getMutations } = await createViewerPolicyServer();
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user