This commit is contained in:
2026-03-17 13:04:16 -04:00
parent 103b59127e
commit 39a8ddef97
8 changed files with 1076 additions and 349 deletions

View File

@@ -1,23 +1,18 @@
// Shared permission keys for agent permissions plugin // Shared permission keys for agent permissions plugin
// Only the single real enforced permission is exposed here.
export const PERMISSION_KEYS = [ export const PERMISSION_KEYS = [
"agents:create", "canCreateAgents",
"users:invite",
"users:manage_permissions",
"tasks:assign",
"tasks:assign_scope",
"joins:approve"
] as const; ] as const;
export type PermissionKey = typeof PERMISSION_KEYS[number]; export type PermissionKey = typeof PERMISSION_KEYS[number];
export const PERMISSION_LABELS: Record<PermissionKey, string> = { export const PERMISSION_LABELS: Record<PermissionKey, string> = {
"agents:create": "Create Agents", "canCreateAgents": "Can Hire Agents",
"users:invite": "Invite Users", };
"users:manage_permissions": "Manage Permissions",
"tasks:assign": "Assign Tasks", export const PERMISSION_DESCRIPTIONS: Record<PermissionKey, string> = {
"tasks:assign_scope": "Task Assignment Scope", "canCreateAgents": "Allows this agent to create (hire) new agents",
"joins:approve": "Approve Join Requests"
}; };
// Pagination constants // Pagination constants

View File

@@ -10,8 +10,7 @@ const manifest: PaperclipPluginManifestV1 = {
categories: ["ui", "automation"], categories: ["ui", "automation"],
capabilities: [ capabilities: [
"agents.read", "agents.read",
"plugin.state.read", "agents.update-permissions",
"plugin.state.write",
"ui.detailTab.register", "ui.detailTab.register",
"ui.page.register", "ui.page.register",
"instance.settings.register" "instance.settings.register"
@@ -27,7 +26,7 @@ const manifest: PaperclipPluginManifestV1 = {
id: "permissions-page", id: "permissions-page",
displayName: "Permissions", displayName: "Permissions",
exportName: "PermissionsPage", exportName: "PermissionsPage",
routePath: "/permissions" routePath: "permissions"
}, },
{ {
type: "settingsPage", type: "settingsPage",

View File

@@ -1,18 +1,24 @@
import { useState } from "react"; import { useState } from "react";
import { usePluginData, usePluginAction } from "@paperclipai/plugin-sdk/ui"; import { usePluginData, usePluginAction } from "@paperclipai/plugin-sdk/ui";
import type { PluginDetailTabProps } from "@paperclipai/plugin-sdk/ui"; import type { PluginDetailTabProps } from "@paperclipai/plugin-sdk/ui";
import { PERMISSION_KEYS, PERMISSION_LABELS, type PermissionKey } from "../constants"; import { PERMISSION_LABELS, PERMISSION_DESCRIPTIONS } from "../constants";
interface AgentPermissionsData {
agentId: string;
agentName: string;
canCreateAgents: boolean;
}
export function AgentPermissionsTab({ context }: PluginDetailTabProps) { export function AgentPermissionsTab({ context }: PluginDetailTabProps) {
const { entityId: agentId } = context; const { entityId: agentId, companyId } = context;
const { data, loading, error, refresh } = usePluginData<{ const { data, loading, error, refresh } = usePluginData<AgentPermissionsData>(
agentId: string; "agent-permissions",
permissions: Record<PermissionKey, boolean>; { agentId, companyId }
}>("agent-permissions", { agentId }); );
const togglePermission = usePluginAction("toggle-agent-permission"); const togglePermission = usePluginAction("toggle-agent-permission");
const [updating, setUpdating] = useState<PermissionKey | null>(null); const [updating, setUpdating] = useState(false);
const [lastError, setLastError] = useState<Error | null>(null); const [lastError, setLastError] = useState<Error | null>(null);
if (loading) return <div style={{ padding: "1rem" }}>Loading permissions...</div>; if (loading) return <div style={{ padding: "1rem" }}>Loading permissions...</div>;
@@ -23,18 +29,18 @@ export function AgentPermissionsTab({ context }: PluginDetailTabProps) {
); );
if (!data) return <div style={{ padding: "1rem" }}>No permissions data available</div>; if (!data) return <div style={{ padding: "1rem" }}>No permissions data available</div>;
async function handleToggle(permissionKey: PermissionKey, currentEnabled: boolean) { async function handleToggle(currentEnabled: boolean) {
setLastError(null); setLastError(null);
setUpdating(permissionKey); setUpdating(true);
try { try {
await togglePermission({ agentId, permissionKey, enabled: !currentEnabled }); await togglePermission({ agentId, companyId, enabled: !currentEnabled });
await refresh(); await refresh();
} catch (err) { } catch (err) {
const error = err instanceof Error ? err : new Error(String(err)); const e = err instanceof Error ? err : new Error(String(err));
setLastError(error); setLastError(e);
console.error("Failed to toggle permission:", error); console.error("Failed to toggle permission:", e);
} finally { } finally {
setUpdating(null); setUpdating(false);
} }
} }
@@ -44,13 +50,13 @@ export function AgentPermissionsTab({ context }: PluginDetailTabProps) {
<p style={{ color: "#666", marginBottom: "1.5rem" }}> <p style={{ color: "#666", marginBottom: "1.5rem" }}>
Control what actions this agent can perform. Control what actions this agent can perform.
</p> </p>
{lastError && ( {lastError && (
<div <div
role="alert" role="alert"
aria-live="polite" aria-live="polite"
style={{ style={{
padding: "0.75rem", padding: "0.75rem",
marginBottom: "1rem", marginBottom: "1rem",
backgroundColor: "#fee", backgroundColor: "#fee",
border: "1px solid #fcc", border: "1px solid #fcc",
@@ -61,51 +67,48 @@ export function AgentPermissionsTab({ context }: PluginDetailTabProps) {
<strong>Failed to update:</strong> {lastError.message} <strong>Failed to update:</strong> {lastError.message}
</div> </div>
)} )}
<fieldset style={{ border: "none", padding: 0, margin: 0 }}> <fieldset style={{ border: "none", padding: 0, margin: 0 }}>
<legend style={{ display: "none" }}>Permission toggles</legend> <legend style={{ display: "none" }}>Permission toggles</legend>
<div style={{ display: "flex", flexDirection: "column", gap: "0.75rem" }}> <div style={{ display: "flex", flexDirection: "column", gap: "0.75rem" }}>
{PERMISSION_KEYS.map((key) => { <label
const enabled = data.permissions[key] ?? false; htmlFor="perm-canCreateAgents"
const isUpdating = updating === key; style={{
display: "flex",
return ( alignItems: "center",
<label gap: "0.75rem",
key={key} cursor: updating ? "wait" : "pointer",
htmlFor={`perm-${key}`} padding: "0.5rem",
style={{ borderRadius: "4px",
display: "flex", backgroundColor: updating ? "#f5f5f5" : "transparent",
alignItems: "center", transition: "background-color 0.2s"
gap: "0.75rem", }}
cursor: isUpdating ? "wait" : "pointer", >
padding: "0.5rem", <input
borderRadius: "4px", id="perm-canCreateAgents"
backgroundColor: isUpdating ? "#f5f5f5" : "transparent", type="checkbox"
transition: "background-color 0.2s" checked={data.canCreateAgents}
}} onChange={() => handleToggle(data.canCreateAgents)}
disabled={updating}
style={{ width: "18px", height: "18px", cursor: updating ? "wait" : "pointer" }}
/>
<span>
<span style={{ fontWeight: 500, display: "block" }}>
{PERMISSION_LABELS["canCreateAgents"]}
</span>
<span style={{ color: "#666", fontSize: "0.875rem" }}>
{PERMISSION_DESCRIPTIONS["canCreateAgents"]}
</span>
</span>
{updating && (
<span
style={{ color: "#888", fontSize: "0.875rem" }}
role="status"
> >
<input updating...
id={`perm-${key}`} </span>
type="checkbox" )}
checked={enabled} </label>
onChange={() => handleToggle(key, enabled)}
disabled={updating !== null}
aria-describedby={isUpdating ? `loading-${key}` : undefined}
style={{ width: "18px", height: "18px", cursor: isUpdating ? "wait" : "pointer" }}
/>
<span style={{ fontWeight: 500 }}>{PERMISSION_LABELS[key]}</span>
{isUpdating && (
<span
id={`loading-${key}`}
style={{ color: "#888", fontSize: "0.875rem" }}
role="status"
>
updating...
</span>
)}
</label>
);
})}
</div> </div>
</fieldset> </fieldset>
</div> </div>

View File

@@ -0,0 +1,70 @@
import { usePluginData, useHostContext } from "@paperclipai/plugin-sdk/ui";
import type { PluginSidebarProps } from "@paperclipai/plugin-sdk/ui";
import { SIDEBAR_PREVIEW_LIMIT, type PermissionKey } from "../constants";
interface AgentPermissionsSummary {
agentId: string;
agentName: string;
permissions: Record<PermissionKey, boolean>;
}
export function PermissionsNav(_props: PluginSidebarProps) {
const { companyId } = useHostContext();
const { data: agentsData, loading, error } = usePluginData<AgentPermissionsSummary[]>(
"all-agents-permissions",
companyId ? { companyId } : undefined
);
if (loading) return (
<div role="status" style={{ padding: "1rem" }}>
Loading permissions...
</div>
);
if (error) return (
<div role="alert" style={{ padding: "1rem", color: "#c00" }}>
<strong>Error:</strong> {error.message}
</div>
);
if (!agentsData || agentsData.length === 0) {
return (
<div style={{ padding: "1rem" }}>
<h3 style={{ fontSize: "1rem", fontWeight: 600, marginBottom: "0.5rem" }}>Permissions</h3>
<p style={{ color: "#666", fontSize: "0.875rem" }}>No agents found</p>
</div>
);
}
const agentsWithPermissions = agentsData.filter(a =>
Object.values(a.permissions).some(v => v)
);
return (
<div style={{ padding: "1rem" }}>
<h3 id="permissions-nav-heading" style={{ fontSize: "1rem", fontWeight: 600, marginBottom: "0.75rem" }}>Permissions</h3>
<p aria-labelledby="permissions-nav-heading" style={{ color: "#666", fontSize: "0.75rem", marginBottom: "1rem" }}>
{agentsWithPermissions.length} agent(s) with custom permissions
</p>
<ul style={{ display: "flex", flexDirection: "column", gap: "0.5rem", padding: 0, margin: 0, listStyle: "none" }}>
{agentsData.slice(0, SIDEBAR_PREVIEW_LIMIT).map(agent => {
const permCount = Object.values(agent.permissions).filter(Boolean).length;
return (
<li
key={agent.agentId}
style={{
fontSize: "0.875rem",
padding: "0.5rem",
backgroundColor: "#f9f9f9",
borderRadius: "4px"
}}
>
<div style={{ fontWeight: 500 }}>{agent.agentName}</div>
<div style={{ color: "#888", fontSize: "0.75rem" }}>
{permCount} permission(s) granted
</div>
</li>
);
})}
</ul>
</div>
);
}

View File

@@ -1,32 +1,32 @@
import { useState } from "react"; import { useState } from "react";
import { usePluginData, usePluginAction, useHostContext } from "@paperclipai/plugin-sdk/ui"; import { usePluginData, usePluginAction, useHostContext } from "@paperclipai/plugin-sdk/ui";
import type { PluginPageProps } from "@paperclipai/plugin-sdk/ui"; import type { PluginPageProps } from "@paperclipai/plugin-sdk/ui";
import { PERMISSION_KEYS, PERMISSION_LABELS, type PermissionKey } from "../constants"; import { PERMISSION_LABELS, PERMISSION_DESCRIPTIONS } from "../constants";
interface AgentPermissionsSummary { interface AgentPermissionsSummary {
agentId: string; agentId: string;
agentName: string; agentName: string;
permissions: Record<PermissionKey, boolean>; canCreateAgents: boolean;
} }
export function PermissionsPage(_props: PluginPageProps) { export function PermissionsPage(_props: PluginPageProps) {
const { companyId } = useHostContext(); const { companyId } = useHostContext();
const { data: agentsData, loading, error, refresh } = usePluginData<AgentPermissionsSummary[]>( const { data: agentsData, loading, error, refresh } = usePluginData<AgentPermissionsSummary[]>(
"all-agents-permissions", "all-agents-permissions",
companyId ? { companyId, limit: 100 } : {} companyId ? { companyId, limit: 100 } : {}
); );
const togglePermission = usePluginAction("toggle-agent-permission"); const togglePermission = usePluginAction("toggle-agent-permission");
const [updating, setUpdating] = useState<{ agentId: string; permissionKey: PermissionKey } | null>(null); const [updating, setUpdating] = useState<string | null>(null);
const [lastError, setLastError] = useState<Error | null>(null); const [lastError, setLastError] = useState<Error | null>(null);
const [expandedAgents, setExpandedAgents] = useState<Set<string>>(new Set()); const [expandedAgents, setExpandedAgents] = useState<Set<string>>(new Set());
async function handleToggle(agentId: string, permissionKey: PermissionKey, currentEnabled: boolean) { async function handleToggle(agentId: string, currentEnabled: boolean) {
setLastError(null); setLastError(null);
setUpdating({ agentId, permissionKey }); setUpdating(agentId);
try { try {
await togglePermission({ agentId, permissionKey, enabled: !currentEnabled }); await togglePermission({ agentId, companyId, enabled: !currentEnabled });
await refresh(); await refresh();
} catch (err) { } catch (err) {
const error = err instanceof Error ? err : new Error(String(err)); const error = err instanceof Error ? err : new Error(String(err));
@@ -86,11 +86,11 @@ export function PermissionsPage(_props: PluginPageProps) {
</header> </header>
{lastError && ( {lastError && (
<div <div
role="alert" role="alert"
aria-live="polite" aria-live="polite"
style={{ style={{
padding: "0.75rem", padding: "0.75rem",
marginBottom: "1rem", marginBottom: "1rem",
backgroundColor: "#fee", backgroundColor: "#fee",
border: "1px solid #fcc", border: "1px solid #fcc",
@@ -104,14 +104,14 @@ export function PermissionsPage(_props: PluginPageProps) {
<div style={{ display: "flex", flexDirection: "column", gap: "1rem" }}> <div style={{ display: "flex", flexDirection: "column", gap: "1rem" }}>
{agentsData.map(agent => { {agentsData.map(agent => {
const permCount = Object.values(agent.permissions).filter(Boolean).length;
const isExpanded = expandedAgents.has(agent.agentId); const isExpanded = expandedAgents.has(agent.agentId);
const isUpdating = updating === agent.agentId;
return ( return (
<div <div
key={agent.agentId} key={agent.agentId}
style={{ style={{
border: "1px solid #e5e7eb", border: "1px solid #e5e7eb",
borderRadius: "8px", borderRadius: "8px",
backgroundColor: "#fff" backgroundColor: "#fff"
}} }}
@@ -135,8 +135,8 @@ export function PermissionsPage(_props: PluginPageProps) {
}} }}
> >
<div style={{ display: "flex", alignItems: "center", gap: "0.75rem" }}> <div style={{ display: "flex", alignItems: "center", gap: "0.75rem" }}>
<span <span
style={{ style={{
transform: isExpanded ? "rotate(90deg)" : "rotate(0deg)", transform: isExpanded ? "rotate(90deg)" : "rotate(0deg)",
transition: "transform 0.2s", transition: "transform 0.2s",
display: "inline-block" display: "inline-block"
@@ -146,71 +146,58 @@ export function PermissionsPage(_props: PluginPageProps) {
</span> </span>
<span>{agent.agentName}</span> <span>{agent.agentName}</span>
</div> </div>
{permCount > 0 && ( {agent.canCreateAgents && (
<span style={{ <span style={{
fontSize: "0.75rem", fontSize: "0.75rem",
backgroundColor: "#e5e7eb", backgroundColor: "#e5e7eb",
color: "#666", color: "#666",
padding: "0.125rem 0.5rem", padding: "0.125rem 0.5rem",
borderRadius: "999px" borderRadius: "999px"
}}> }}>
{permCount} permission(s) can hire
</span> </span>
)} )}
</button> </button>
{isExpanded && ( {isExpanded && (
<div style={{ padding: "0 1.25rem 1.25rem" }}> <div style={{ padding: "0 1.25rem 1.25rem" }}>
<fieldset style={{ border: "none", padding: 0, margin: 0 }}> <fieldset style={{ border: "none", padding: 0, margin: 0 }}>
<legend style={{ display: "none" }}>Permission toggles for {agent.agentName}</legend> <legend style={{ display: "none" }}>Permission toggles for {agent.agentName}</legend>
<div style={{ display: "flex", flexDirection: "column", gap: "0.75rem", marginTop: "0.5rem" }}> <div style={{ display: "flex", flexDirection: "column", gap: "0.75rem", marginTop: "0.5rem" }}>
{PERMISSION_KEYS.map((key) => { <label
const enabled = agent.permissions[key] ?? false; htmlFor={`perm-${agent.agentId}-canCreateAgents`}
const isUpdating = updating?.agentId === agent.agentId && updating?.permissionKey === key; style={{
display: "flex",
return ( alignItems: "center",
<label gap: "0.75rem",
key={key} cursor: isUpdating ? "wait" : "pointer",
htmlFor={`perm-${agent.agentId}-${key}`} padding: "0.75rem",
style={{ borderRadius: "6px",
display: "flex", backgroundColor: isUpdating ? "#f9fafb" : "#fafafa",
alignItems: "center", border: "1px solid #e5e7eb",
gap: "0.75rem", transition: "background-color 0.2s"
cursor: isUpdating ? "wait" : "pointer", }}
padding: "0.75rem", >
borderRadius: "6px", <input
backgroundColor: isUpdating ? "#f9fafb" : "#fafafa", id={`perm-${agent.agentId}-canCreateAgents`}
border: "1px solid #e5e7eb", type="checkbox"
transition: "background-color 0.2s" checked={agent.canCreateAgents}
}} onChange={() => handleToggle(agent.agentId, agent.canCreateAgents)}
> disabled={updating !== null}
<input style={{ width: "18px", height: "18px", cursor: isUpdating ? "wait" : "pointer" }}
id={`perm-${agent.agentId}-${key}`} />
type="checkbox" <div style={{ flex: 1 }}>
checked={enabled} <div style={{ fontWeight: 500 }}>{PERMISSION_LABELS["canCreateAgents"]}</div>
onChange={() => handleToggle(agent.agentId, key, enabled)} <div style={{ fontSize: "0.75rem", color: "#666" }}>
disabled={updating !== null} {PERMISSION_DESCRIPTIONS["canCreateAgents"]}
aria-describedby={isUpdating ? `loading-${agent.agentId}-${key}` : undefined} </div>
style={{ width: "18px", height: "18px", cursor: isUpdating ? "wait" : "pointer" }} </div>
/> {isUpdating && (
<div style={{ flex: 1 }}> <span style={{ color: "#888", fontSize: "0.75rem" }} role="status">
<div style={{ fontWeight: 500 }}>{PERMISSION_LABELS[key]}</div> updating...
<div style={{ fontSize: "0.75rem", color: "#666" }}> </span>
{getPermissionDescription(key)} )}
</div> </label>
</div>
{isUpdating && (
<span
id={`loading-${agent.agentId}-${key}`}
style={{ color: "#888", fontSize: "0.75rem" }}
role="status"
>
updating...
</span>
)}
</label>
);
})}
</div> </div>
</fieldset> </fieldset>
</div> </div>
@@ -222,15 +209,3 @@ export function PermissionsPage(_props: PluginPageProps) {
</div> </div>
); );
} }
function getPermissionDescription(key: PermissionKey): string {
const descriptions: Record<PermissionKey, string> = {
"agents:create": "Allows this agent to create new agents (agent hiring)",
"users:invite": "Allows inviting board users to the company",
"users:manage_permissions": "Allows managing user permissions",
"tasks:assign": "Allows assigning tasks to agents",
"tasks:assign_scope": "Scope for task assignment (limits which agents can be assigned)",
"joins:approve": "Allows approving join requests"
};
return descriptions[key];
}

View File

@@ -1,17 +1,13 @@
import { useState } from "react"; import { useState } from "react";
import { useHostContext, usePluginData, usePluginAction, usePluginToast, type PluginSettingsPageProps } from "@paperclipai/plugin-sdk/ui"; import { usePluginData, usePluginAction, usePluginToast } from "@paperclipai/plugin-sdk/ui";
import type { PluginSettingsPageProps } from "@paperclipai/plugin-sdk/ui";
import { PERMISSION_LABELS, PERMISSION_DESCRIPTIONS } from "../constants";
type Permission = { interface AgentPermissionsSummary {
capability: string; agentId: string;
allowed: boolean; agentName: string;
}; canCreateAgents: boolean;
}
type AgentRecord = {
id: string;
name: string;
status: string;
description?: string | null;
};
const layoutStyle = { const layoutStyle = {
display: "grid", display: "grid",
@@ -23,7 +19,7 @@ const cardStyle = {
borderRadius: "12px", borderRadius: "12px",
overflow: "hidden", overflow: "hidden",
background: "var(--card, transparent)", background: "var(--card, transparent)",
};; };
const headerStyle = { const headerStyle = {
display: "flex", display: "flex",
@@ -32,14 +28,13 @@ const headerStyle = {
padding: "14px 16px", padding: "14px 16px",
cursor: "pointer", cursor: "pointer",
background: "color-mix(in srgb, var(--muted, #888) 6%, transparent)", background: "color-mix(in srgb, var(--muted, #888) 6%, transparent)",
userSelect: "none",
}; };
const contentStyle = { const contentStyle = {
padding: "14px 16px 16px", padding: "14px 16px 16px",
display: "grid", display: "grid",
gap: "12px", gap: "12px",
};; };
const permissionRowStyle = { const permissionRowStyle = {
display: "flex", display: "flex",
@@ -49,13 +44,13 @@ const permissionRowStyle = {
padding: "8px 10px", padding: "8px 10px",
borderRadius: "8px", borderRadius: "8px",
border: "1px solid color-mix(in srgb, var(--border) 60%, transparent)", border: "1px solid color-mix(in srgb, var(--border) 60%, transparent)",
};; };
const mutedTextStyle = { const mutedTextStyle = {
fontSize: "12px", fontSize: "12px",
opacity: 0.72, opacity: 0.72,
lineHeight: 1.45, lineHeight: 1.45,
};; };
function ChevronIcon({ expanded }: { expanded: boolean }) { function ChevronIcon({ expanded }: { expanded: boolean }) {
return ( return (
@@ -67,6 +62,7 @@ function ChevronIcon({ expanded }: { expanded: boolean }) {
style={{ style={{
transition: "transform 0.15s ease", transition: "transform 0.15s ease",
transform: expanded ? "rotate(180deg)" : "rotate(0deg)", transform: expanded ? "rotate(180deg)" : "rotate(0deg)",
flexShrink: 0,
}} }}
> >
<path d="M4 6L8 10L12 6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /> <path d="M4 6L8 10L12 6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
@@ -74,40 +70,19 @@ function ChevronIcon({ expanded }: { expanded: boolean }) {
); );
} }
function StatusBadge({ status }: { status: string }) {
const isActive = status === "active";
return (
<span
style={{
fontSize: "11px",
padding: "2px 8px",
borderRadius: "999px",
border: "1px solid var(--border)",
background: isActive ? "color-mix(in srgb, #16a34a 15%, transparent)" : "transparent",
color: isActive ? "#86efac" : "inherit",
}}
>
{status}
</span>
);
}
export function PermissionsSettingsPage({ context }: PluginSettingsPageProps) { export function PermissionsSettingsPage({ context }: PluginSettingsPageProps) {
const companyId = context.companyId; const companyId = context.companyId;
const agentsQuery = usePluginData<AgentRecord[]>("agents", companyId ? { companyId } : {}); const { data: agentsData, loading, error, refresh } = usePluginData<AgentPermissionsSummary[]>(
const permissionsQuery = usePluginData<Permission[]>("agent-permissions", companyId ? { companyId } : {}); "all-agents-permissions",
const updatePermissions = usePluginAction("update-agent-permissions"); companyId ? { companyId, limit: 100 } : {}
);
const togglePermission = usePluginAction("toggle-agent-permission");
const toast = usePluginToast(); const toast = usePluginToast();
const [expandedAgents, setExpandedAgents] = useState<Set<string>>(new Set()); const [expandedAgents, setExpandedAgents] = useState<Set<string>>(new Set());
const [updating, setUpdating] = useState<string | null>(null);
const agents = agentsQuery.data ?? [];
const allPermissions = permissionsQuery.data ?? [];
function getAgentPermissions(agentId: string): Permission[] {
return allPermissions.filter((p) => p.capability.startsWith(`${agentId}:`));
}
function handleToggleAgent(agentId: string) { function handleToggleAgent(agentId: string) {
setExpandedAgents((prev) => { setExpandedAgents((prev) => {
@@ -121,29 +96,25 @@ export function PermissionsSettingsPage({ context }: PluginSettingsPageProps) {
}); });
} }
async function handleTogglePermission(agentId: string, capability: string, newValue: boolean) { async function handleToggle(agentId: string, currentEnabled: boolean) {
if (!companyId) return; setUpdating(agentId);
try { try {
await updatePermissions({ await togglePermission({ agentId, companyId, enabled: !currentEnabled });
companyId, await refresh();
agentId,
capability,
allowed: newValue,
});
permissionsQuery.refresh();
toast({ toast({
title: "Permission updated", title: "Permission updated",
body: `${capability}: ${newValue ? "allowed" : "denied"}`, body: `${PERMISSION_LABELS["canCreateAgents"]}: ${!currentEnabled ? "allowed" : "denied"}`,
tone: "success", tone: "success",
}); });
} catch (error) { } catch (err) {
const message = error instanceof Error ? error.message : String(error); const message = err instanceof Error ? err.message : String(err);
toast({ toast({
title: "Failed to update permission", title: "Failed to update permission",
body: message, body: message,
tone: "error", tone: "error",
}); });
} finally {
setUpdating(null);
} }
} }
@@ -157,7 +128,7 @@ export function PermissionsSettingsPage({ context }: PluginSettingsPageProps) {
); );
} }
if (agentsQuery.loading || permissionsQuery.loading) { if (loading) {
return ( return (
<div style={layoutStyle}> <div style={layoutStyle}>
<div style={{ fontSize: "13px", opacity: 0.7 }}> <div style={{ fontSize: "13px", opacity: 0.7 }}>
@@ -167,7 +138,17 @@ export function PermissionsSettingsPage({ context }: PluginSettingsPageProps) {
); );
} }
if (agents.length === 0) { if (error) {
return (
<div style={layoutStyle}>
<div style={{ fontSize: "13px", color: "var(--destructive, #c00)" }}>
Failed to load: {error.message}
</div>
</div>
);
}
if (!agentsData || agentsData.length === 0) {
return ( return (
<div style={layoutStyle}> <div style={layoutStyle}>
<div style={{ fontSize: "13px", opacity: 0.7 }}> <div style={{ fontSize: "13px", opacity: 0.7 }}>
@@ -180,74 +161,57 @@ export function PermissionsSettingsPage({ context }: PluginSettingsPageProps) {
return ( return (
<div style={layoutStyle}> <div style={layoutStyle}>
<div style={{ display: "grid", gap: "6px" }}> <div style={{ display: "grid", gap: "6px" }}>
<strong>Agent Permissions</strong>
<div style={mutedTextStyle}> <div style={mutedTextStyle}>
Manage permissions for each agent in your company. Toggle capabilities to allow or deny specific actions. Toggle hiring permission to allow or deny each agent from creating new agents.
</div> </div>
</div> </div>
<div style={{ display: "grid", gap: "10px" }}> <div style={{ display: "grid", gap: "10px" }}>
{agents.map((agent) => { {agentsData.map((agent) => {
const isExpanded = expandedAgents.has(agent.id); const isExpanded = expandedAgents.has(agent.agentId);
const agentPermissions = getAgentPermissions(agent.id); const isUpdating = updating === agent.agentId;
return ( return (
<div key={agent.id} style={cardStyle}> <div key={agent.agentId} style={cardStyle}>
<div style={headerStyle} onClick={() => handleToggleAgent(agent.id)}> <div style={headerStyle} onClick={() => handleToggleAgent(agent.agentId)}>
<ChevronIcon expanded={isExpanded} /> <ChevronIcon expanded={isExpanded} />
<div style={{ display: "grid", gap: "2px", flex: 1 }}> <div style={{ display: "grid", gap: "2px", flex: 1 }}>
<div style={{ display: "flex", alignItems: "center", gap: "8px" }}> <strong style={{ fontSize: "13px" }}>{agent.agentName}</strong>
<strong style={{ fontSize: "13px" }}>{agent.name}</strong>
<StatusBadge status={agent.status} />
</div>
{agent.description ? (
<div style={{ ...mutedTextStyle, fontSize: "12px" }}>{agent.description}</div>
) : null}
</div> </div>
<span style={{ ...mutedTextStyle, fontSize: "11px" }}> {agent.canCreateAgents && (
{agentPermissions.length} permissions <span style={{ ...mutedTextStyle, fontSize: "11px" }}>
</span> can hire
</span>
)}
</div> </div>
{isExpanded ? ( {isExpanded ? (
<div style={contentStyle}> <div style={contentStyle}>
{agentPermissions.length === 0 ? ( <div style={{ display: "grid", gap: "8px" }}>
<div style={{ ...mutedTextStyle, fontSize: "12px" }}> <div style={permissionRowStyle}>
No custom permissions configured for this agent. <div style={{ display: "grid", gap: "2px", flex: 1 }}>
<div style={{ fontSize: "12px", fontWeight: 500 }}>{PERMISSION_LABELS["canCreateAgents"]}</div>
<div style={{ ...mutedTextStyle, fontSize: "11px" }}>{PERMISSION_DESCRIPTIONS["canCreateAgents"]}</div>
</div>
<label style={{ display: "flex", alignItems: "center", gap: "6px", cursor: isUpdating ? "wait" : "pointer" }}>
<input
type="checkbox"
checked={agent.canCreateAgents}
disabled={updating !== null}
onChange={() => handleToggle(agent.agentId, agent.canCreateAgents)}
style={{
width: "16px",
height: "16px",
accentColor: "var(--foreground)",
cursor: isUpdating ? "wait" : "pointer",
}}
/>
<span style={{ fontSize: "11px", opacity: 0.8 }}>
{isUpdating ? "saving…" : agent.canCreateAgents ? "Allowed" : "Denied"}
</span>
</label>
</div> </div>
) : ( </div>
<div style={{ display: "grid", gap: "8px" }}>
{agentPermissions.map((permission) => {
const capabilityName = permission.capability.replace(`${agent.id}:`, "");
return (
<div key={permission.capability} style={permissionRowStyle}>
<div style={{ display: "grid", gap: "2px", flex: 1 }}>
<div style={{ fontSize: "12px" }}>{capabilityName}</div>
<div style={{ ...mutedTextStyle, fontSize: "11px" }}>
{permission.capability}
</div>
</div>
<label style={{ display: "flex", alignItems: "center", gap: "6px", cursor: "pointer" }}>
<input
type="checkbox"
checked={permission.allowed}
onChange={(e) => handleTogglePermission(agent.id, permission.capability, e.target.checked)}
style={{
width: "16px",
height: "16px",
accentColor: "var(--foreground)",
}}
/>
<span style={{ fontSize: "11px" }}>
{permission.allowed ? "Allowed" : "Denied"}
</span>
</label>
</div>
);
})}
</div>
)}
</div> </div>
) : null} ) : null}
</div> </div>

View File

@@ -1,77 +1,36 @@
import { definePlugin, runWorker } from "@paperclipai/plugin-sdk"; import { definePlugin, runWorker } from "@paperclipai/plugin-sdk";
import { import { DEFAULT_PAGE_LIMIT, MAX_PAGE_LIMIT } from "./constants";
PERMISSION_KEYS,
type PermissionKey,
DEFAULT_PAGE_LIMIT,
MAX_PAGE_LIMIT
} from "./constants";
interface AgentPermissions { interface AgentPermissionsSummary {
agentId: string;
permissions: Record<PermissionKey, boolean>;
}
interface AllAgentsPermissions {
agentId: string; agentId: string;
agentName: string; agentName: string;
permissions: Record<PermissionKey, boolean>; canCreateAgents: boolean;
} }
type AgentPermissionsMap = Record<string, Record<PermissionKey, boolean>>;
const plugin = definePlugin({ const plugin = definePlugin({
async setup(ctx) { async setup(ctx) {
// Per-agent data for the detail tab
ctx.data.register("agent-permissions", async (params) => { ctx.data.register("agent-permissions", async (params) => {
const { agentId } = params as { agentId: string }; const agentId = typeof params.agentId === "string" ? params.agentId : "";
const companyId = typeof params.companyId === "string" ? params.companyId : "";
const allPerms = (await ctx.state.get(
{ scopeKind: "instance", stateKey: "agent_permissions" } if (!agentId) return null;
) as AgentPermissionsMap) ?? {};
// companyId may be empty when called from the detail tab; we still try
const agentPerms = allPerms[agentId] ?? {}; const agent = companyId
? await ctx.agents.get(agentId, companyId)
: null;
if (!agent) return null;
return { return {
agentId, agentId: agent.id,
permissions: PERMISSION_KEYS.reduce((acc, key) => ({ agentName: agent.name,
...acc, canCreateAgents: agent.permissions?.canCreateAgents ?? false,
[key]: agentPerms[key] ?? false
}), {} as Record<PermissionKey, boolean>)
}; };
}); });
ctx.actions.register("toggle-agent-permission", async (params) => { // All-agents list for the permissions page and settings page
const { agentId, permissionKey, enabled } = params as {
agentId: string;
permissionKey: PermissionKey;
enabled: boolean;
};
// Input validation
if (!agentId || typeof agentId !== 'string') {
throw new Error('Invalid agentId: must be a non-empty string');
}
if (!PERMISSION_KEYS.includes(permissionKey)) {
throw new Error(`Invalid permission key: ${permissionKey}`);
}
if (typeof enabled !== 'boolean') {
throw new Error('Invalid enabled: must be a boolean');
}
const allPerms = (await ctx.state.get(
{ scopeKind: "instance", stateKey: "agent_permissions" }
) as AgentPermissionsMap) ?? {};
const agentPerms = allPerms[agentId] ?? {};
const updated = { ...agentPerms, [permissionKey]: enabled };
await ctx.state.set(
{ scopeKind: "instance", stateKey: "agent_permissions" },
{ ...allPerms, [agentId]: updated }
);
return { success: true };
});
ctx.data.register("all-agents-permissions", async (params) => { ctx.data.register("all-agents-permissions", async (params) => {
const companyId = typeof params.companyId === "string" ? params.companyId : ""; const companyId = typeof params.companyId === "string" ? params.companyId : "";
const limit = Math.min( const limit = Math.min(
@@ -79,26 +38,43 @@ const plugin = definePlugin({
MAX_PAGE_LIMIT MAX_PAGE_LIMIT
); );
const offset = Math.max(0, Number(params.offset) || 0); const offset = Math.max(0, Number(params.offset) || 0);
const agents = companyId const agents = companyId
? await ctx.agents.list({ companyId, limit, offset }) ? await ctx.agents.list({ companyId, limit, offset })
: []; : [];
const allPerms = (await ctx.state.get( const result: AgentPermissionsSummary[] = agents.map(agent => ({
{ scopeKind: "instance", stateKey: "agent_permissions" }
) as AgentPermissionsMap) ?? {};
const result: AllAgentsPermissions[] = agents.map(agent => ({
agentId: agent.id, agentId: agent.id,
agentName: agent.name, agentName: agent.name,
permissions: PERMISSION_KEYS.reduce((acc, key) => ({ canCreateAgents: agent.permissions?.canCreateAgents ?? false,
...acc,
[key]: allPerms[agent.id]?.[key] ?? false
}), {} as Record<PermissionKey, boolean>)
})); }));
return result; return result;
}); });
ctx.actions.register("toggle-agent-permission", async (params) => {
const { agentId, companyId, enabled } = params as {
agentId: string;
companyId: string;
enabled: boolean;
};
if (!agentId || typeof agentId !== "string") {
throw new Error("Invalid agentId: must be a non-empty string");
}
if (!companyId || typeof companyId !== "string") {
throw new Error("Invalid companyId: must be a non-empty string");
}
if (typeof enabled !== "boolean") {
throw new Error("Invalid enabled: must be a boolean");
}
await ctx.agents.updatePermissions(agentId, companyId, {
canCreateAgents: enabled,
});
return { success: true };
});
}, },
async onHealth() { async onHealth() {

745
testing.ts Normal file
View File

@@ -0,0 +1,745 @@
import { randomUUID } from "node:crypto";
import type {
PaperclipPluginManifestV1,
PluginCapability,
PluginEventType,
Company,
Project,
Issue,
IssueComment,
Agent,
Goal,
} from "@paperclipai/shared";
import type {
EventFilter,
PluginContext,
PluginEntityRecord,
PluginEntityUpsert,
PluginJobContext,
PluginLauncherRegistration,
PluginEvent,
ScopeKey,
ToolResult,
ToolRunContext,
PluginWorkspace,
AgentSession,
AgentSessionEvent,
} from "./types.js";
export interface TestHarnessOptions {
/** Plugin manifest used to seed capability checks and metadata. */
manifest: PaperclipPluginManifestV1;
/** Optional capability override. Defaults to `manifest.capabilities`. */
capabilities?: PluginCapability[];
/** Initial config returned by `ctx.config.get()`. */
config?: Record<string, unknown>;
}
export interface TestHarnessLogEntry {
level: "info" | "warn" | "error" | "debug";
message: string;
meta?: Record<string, unknown>;
}
export interface TestHarness {
/** Fully-typed in-memory plugin context passed to `plugin.setup(ctx)`. */
ctx: PluginContext;
/** Seed host entities for `ctx.companies/projects/issues/agents/goals` reads. */
seed(input: {
companies?: Company[];
projects?: Project[];
issues?: Issue[];
issueComments?: IssueComment[];
agents?: Agent[];
goals?: Goal[];
}): void;
setConfig(config: Record<string, unknown>): void;
/** Dispatch a host or plugin event to registered handlers. */
emit(eventType: PluginEventType | `plugin.${string}`, payload: unknown, base?: Partial<PluginEvent>): Promise<void>;
/** Execute a previously-registered scheduled job handler. */
runJob(jobKey: string, partial?: Partial<PluginJobContext>): Promise<void>;
/** Invoke a `ctx.data.register(...)` handler by key. */
getData<T = unknown>(key: string, params?: Record<string, unknown>): Promise<T>;
/** Invoke a `ctx.actions.register(...)` handler by key. */
performAction<T = unknown>(key: string, params?: Record<string, unknown>): Promise<T>;
/** Execute a registered tool handler via `ctx.tools.execute(...)`. */
executeTool<T = ToolResult>(name: string, params: unknown, runCtx?: Partial<ToolRunContext>): Promise<T>;
/** Read raw in-memory state for assertions. */
getState(input: ScopeKey): unknown;
/** Simulate a streaming event arriving for an active session. */
simulateSessionEvent(sessionId: string, event: Omit<AgentSessionEvent, "sessionId">): void;
logs: TestHarnessLogEntry[];
activity: Array<{ message: string; entityType?: string; entityId?: string; metadata?: Record<string, unknown> }>;
metrics: Array<{ name: string; value: number; tags?: Record<string, string> }>;
}
type EventRegistration = {
name: PluginEventType | `plugin.${string}`;
filter?: EventFilter;
fn: (event: PluginEvent) => Promise<void>;
};
function normalizeScope(input: ScopeKey): Required<Pick<ScopeKey, "scopeKind" | "stateKey">> & Pick<ScopeKey, "scopeId" | "namespace"> {
return {
scopeKind: input.scopeKind,
scopeId: input.scopeId,
namespace: input.namespace ?? "default",
stateKey: input.stateKey,
};
}
function stateMapKey(input: ScopeKey): string {
const normalized = normalizeScope(input);
return `${normalized.scopeKind}|${normalized.scopeId ?? ""}|${normalized.namespace}|${normalized.stateKey}`;
}
function allowsEvent(filter: EventFilter | undefined, event: PluginEvent): boolean {
if (!filter) return true;
if (filter.companyId && filter.companyId !== String((event.payload as Record<string, unknown> | undefined)?.companyId ?? "")) return false;
if (filter.projectId && filter.projectId !== String((event.payload as Record<string, unknown> | undefined)?.projectId ?? "")) return false;
if (filter.agentId && filter.agentId !== String((event.payload as Record<string, unknown> | undefined)?.agentId ?? "")) return false;
return true;
}
function requireCapability(manifest: PaperclipPluginManifestV1, allowed: Set<PluginCapability>, capability: PluginCapability) {
if (allowed.has(capability)) return;
throw new Error(`Plugin '${manifest.id}' is missing required capability '${capability}' in test harness`);
}
function requireCompanyId(companyId?: string): string {
if (!companyId) throw new Error("companyId is required for this operation");
return companyId;
}
function isInCompany<T extends { companyId: string | null | undefined }>(
record: T | null | undefined,
companyId: string,
): record is T {
return Boolean(record && record.companyId === companyId);
}
/**
* Create an in-memory host harness for plugin worker tests.
*
* The harness enforces declared capabilities and simulates host APIs, so tests
* can validate plugin behavior without spinning up the Paperclip server runtime.
*/
export function createTestHarness(options: TestHarnessOptions): TestHarness {
const manifest = options.manifest;
const capabilitySet = new Set(options.capabilities ?? manifest.capabilities);
let currentConfig = { ...(options.config ?? {}) };
const logs: TestHarnessLogEntry[] = [];
const activity: TestHarness["activity"] = [];
const metrics: TestHarness["metrics"] = [];
const state = new Map<string, unknown>();
const entities = new Map<string, PluginEntityRecord>();
const entityExternalIndex = new Map<string, string>();
const companies = new Map<string, Company>();
const projects = new Map<string, Project>();
const issues = new Map<string, Issue>();
const issueComments = new Map<string, IssueComment[]>();
const agents = new Map<string, Agent>();
const goals = new Map<string, Goal>();
const projectWorkspaces = new Map<string, PluginWorkspace[]>();
const sessions = new Map<string, AgentSession>();
const sessionEventCallbacks = new Map<string, (event: AgentSessionEvent) => void>();
const events: EventRegistration[] = [];
const jobs = new Map<string, (job: PluginJobContext) => Promise<void>>();
const launchers = new Map<string, PluginLauncherRegistration>();
const dataHandlers = new Map<string, (params: Record<string, unknown>) => Promise<unknown>>();
const actionHandlers = new Map<string, (params: Record<string, unknown>) => Promise<unknown>>();
const toolHandlers = new Map<string, (params: unknown, runCtx: ToolRunContext) => Promise<ToolResult>>();
const ctx: PluginContext = {
manifest,
config: {
async get() {
return { ...currentConfig };
},
},
events: {
on(name: PluginEventType | `plugin.${string}`, filterOrFn: EventFilter | ((event: PluginEvent) => Promise<void>), maybeFn?: (event: PluginEvent) => Promise<void>): () => void {
requireCapability(manifest, capabilitySet, "events.subscribe");
let registration: EventRegistration;
if (typeof filterOrFn === "function") {
registration = { name, fn: filterOrFn };
} else {
if (!maybeFn) throw new Error("event handler is required");
registration = { name, filter: filterOrFn, fn: maybeFn };
}
events.push(registration);
return () => {
const idx = events.indexOf(registration);
if (idx !== -1) events.splice(idx, 1);
};
},
async emit(name, companyId, payload) {
requireCapability(manifest, capabilitySet, "events.emit");
await harness.emit(`plugin.${manifest.id}.${name}`, payload, { companyId });
},
},
jobs: {
register(key, fn) {
requireCapability(manifest, capabilitySet, "jobs.schedule");
jobs.set(key, fn);
},
},
launchers: {
register(launcher) {
launchers.set(launcher.id, launcher);
},
},
http: {
async fetch(url, init) {
requireCapability(manifest, capabilitySet, "http.outbound");
return fetch(url, init);
},
},
secrets: {
async resolve(secretRef) {
requireCapability(manifest, capabilitySet, "secrets.read-ref");
return `resolved:${secretRef}`;
},
},
activity: {
async log(entry) {
requireCapability(manifest, capabilitySet, "activity.log.write");
activity.push(entry);
},
},
state: {
async get(input) {
requireCapability(manifest, capabilitySet, "plugin.state.read");
return state.has(stateMapKey(input)) ? state.get(stateMapKey(input)) : null;
},
async set(input, value) {
requireCapability(manifest, capabilitySet, "plugin.state.write");
state.set(stateMapKey(input), value);
},
async delete(input) {
requireCapability(manifest, capabilitySet, "plugin.state.write");
state.delete(stateMapKey(input));
},
},
entities: {
async upsert(input: PluginEntityUpsert) {
const externalKey = input.externalId
? `${input.entityType}|${input.scopeKind}|${input.scopeId ?? ""}|${input.externalId}`
: null;
const existingId = externalKey ? entityExternalIndex.get(externalKey) : undefined;
const existing = existingId ? entities.get(existingId) : undefined;
const now = new Date().toISOString();
const previousExternalKey = existing?.externalId
? `${existing.entityType}|${existing.scopeKind}|${existing.scopeId ?? ""}|${existing.externalId}`
: null;
const record: PluginEntityRecord = existing
? {
...existing,
entityType: input.entityType,
scopeKind: input.scopeKind,
scopeId: input.scopeId ?? null,
externalId: input.externalId ?? null,
title: input.title ?? null,
status: input.status ?? null,
data: input.data,
updatedAt: now,
}
: {
id: randomUUID(),
entityType: input.entityType,
scopeKind: input.scopeKind,
scopeId: input.scopeId ?? null,
externalId: input.externalId ?? null,
title: input.title ?? null,
status: input.status ?? null,
data: input.data,
createdAt: now,
updatedAt: now,
};
entities.set(record.id, record);
if (previousExternalKey && previousExternalKey !== externalKey) {
entityExternalIndex.delete(previousExternalKey);
}
if (externalKey) entityExternalIndex.set(externalKey, record.id);
return record;
},
async list(query) {
let out = [...entities.values()];
if (query.entityType) out = out.filter((r) => r.entityType === query.entityType);
if (query.scopeKind) out = out.filter((r) => r.scopeKind === query.scopeKind);
if (query.scopeId) out = out.filter((r) => r.scopeId === query.scopeId);
if (query.externalId) out = out.filter((r) => r.externalId === query.externalId);
if (query.offset) out = out.slice(query.offset);
if (query.limit) out = out.slice(0, query.limit);
return out;
},
},
projects: {
async list(input) {
requireCapability(manifest, capabilitySet, "projects.read");
const companyId = requireCompanyId(input?.companyId);
let out = [...projects.values()];
out = out.filter((project) => project.companyId === companyId);
if (input?.offset) out = out.slice(input.offset);
if (input?.limit) out = out.slice(0, input.limit);
return out;
},
async get(projectId, companyId) {
requireCapability(manifest, capabilitySet, "projects.read");
const project = projects.get(projectId);
return isInCompany(project, companyId) ? project : null;
},
async listWorkspaces(projectId, companyId) {
requireCapability(manifest, capabilitySet, "project.workspaces.read");
if (!isInCompany(projects.get(projectId), companyId)) return [];
return projectWorkspaces.get(projectId) ?? [];
},
async getPrimaryWorkspace(projectId, companyId) {
requireCapability(manifest, capabilitySet, "project.workspaces.read");
if (!isInCompany(projects.get(projectId), companyId)) return null;
const workspaces = projectWorkspaces.get(projectId) ?? [];
return workspaces.find((workspace) => workspace.isPrimary) ?? null;
},
async getWorkspaceForIssue(issueId, companyId) {
requireCapability(manifest, capabilitySet, "project.workspaces.read");
const issue = issues.get(issueId);
if (!isInCompany(issue, companyId)) return null;
const projectId = (issue as unknown as Record<string, unknown>)?.projectId as string | undefined;
if (!projectId) return null;
if (!isInCompany(projects.get(projectId), companyId)) return null;
const workspaces = projectWorkspaces.get(projectId) ?? [];
return workspaces.find((workspace) => workspace.isPrimary) ?? null;
},
},
companies: {
async list(input) {
requireCapability(manifest, capabilitySet, "companies.read");
let out = [...companies.values()];
if (input?.offset) out = out.slice(input.offset);
if (input?.limit) out = out.slice(0, input.limit);
return out;
},
async get(companyId) {
requireCapability(manifest, capabilitySet, "companies.read");
return companies.get(companyId) ?? null;
},
},
issues: {
async list(input) {
requireCapability(manifest, capabilitySet, "issues.read");
const companyId = requireCompanyId(input?.companyId);
let out = [...issues.values()];
out = out.filter((issue) => issue.companyId === companyId);
if (input?.projectId) out = out.filter((issue) => issue.projectId === input.projectId);
if (input?.assigneeAgentId) out = out.filter((issue) => issue.assigneeAgentId === input.assigneeAgentId);
if (input?.status) out = out.filter((issue) => issue.status === input.status);
if (input?.offset) out = out.slice(input.offset);
if (input?.limit) out = out.slice(0, input.limit);
return out;
},
async get(issueId, companyId) {
requireCapability(manifest, capabilitySet, "issues.read");
const issue = issues.get(issueId);
return isInCompany(issue, companyId) ? issue : null;
},
async create(input) {
requireCapability(manifest, capabilitySet, "issues.create");
const now = new Date();
const record: Issue = {
id: randomUUID(),
companyId: input.companyId,
projectId: input.projectId ?? null,
goalId: input.goalId ?? null,
parentId: input.parentId ?? null,
title: input.title,
description: input.description ?? null,
status: "todo",
priority: input.priority ?? "medium",
assigneeAgentId: input.assigneeAgentId ?? null,
assigneeUserId: null,
checkoutRunId: null,
executionRunId: null,
executionAgentNameKey: null,
executionLockedAt: null,
createdByAgentId: null,
createdByUserId: null,
issueNumber: null,
identifier: null,
requestDepth: 0,
billingCode: null,
assigneeAdapterOverrides: null,
executionWorkspaceSettings: null,
startedAt: null,
completedAt: null,
cancelledAt: null,
hiddenAt: null,
createdAt: now,
updatedAt: now,
};
issues.set(record.id, record);
return record;
},
async update(issueId, patch, companyId) {
requireCapability(manifest, capabilitySet, "issues.update");
const record = issues.get(issueId);
if (!isInCompany(record, companyId)) throw new Error(`Issue not found: ${issueId}`);
const updated: Issue = {
...record,
...patch,
updatedAt: new Date(),
};
issues.set(issueId, updated);
return updated;
},
async listComments(issueId, companyId) {
requireCapability(manifest, capabilitySet, "issue.comments.read");
if (!isInCompany(issues.get(issueId), companyId)) return [];
return issueComments.get(issueId) ?? [];
},
async createComment(issueId, body, companyId) {
requireCapability(manifest, capabilitySet, "issue.comments.create");
const parentIssue = issues.get(issueId);
if (!isInCompany(parentIssue, companyId)) {
throw new Error(`Issue not found: ${issueId}`);
}
const now = new Date();
const comment: IssueComment = {
id: randomUUID(),
companyId: parentIssue.companyId,
issueId,
authorAgentId: null,
authorUserId: null,
body,
createdAt: now,
updatedAt: now,
};
const current = issueComments.get(issueId) ?? [];
current.push(comment);
issueComments.set(issueId, current);
return comment;
},
documents: {
async list(issueId, companyId) {
requireCapability(manifest, capabilitySet, "issue.documents.read");
if (!isInCompany(issues.get(issueId), companyId)) return [];
return [];
},
async get(issueId, _key, companyId) {
requireCapability(manifest, capabilitySet, "issue.documents.read");
if (!isInCompany(issues.get(issueId), companyId)) return null;
return null;
},
async upsert(input) {
requireCapability(manifest, capabilitySet, "issue.documents.write");
const parentIssue = issues.get(input.issueId);
if (!isInCompany(parentIssue, input.companyId)) {
throw new Error(`Issue not found: ${input.issueId}`);
}
throw new Error("documents.upsert is not implemented in test context");
},
async delete(issueId, _key, companyId) {
requireCapability(manifest, capabilitySet, "issue.documents.write");
const parentIssue = issues.get(issueId);
if (!isInCompany(parentIssue, companyId)) {
throw new Error(`Issue not found: ${issueId}`);
}
},
},
},
agents: {
async list(input) {
requireCapability(manifest, capabilitySet, "agents.read");
const companyId = requireCompanyId(input?.companyId);
let out = [...agents.values()];
out = out.filter((agent) => agent.companyId === companyId);
if (input?.status) out = out.filter((agent) => agent.status === input.status);
if (input?.offset) out = out.slice(input.offset);
if (input?.limit) out = out.slice(0, input.limit);
return out;
},
async get(agentId, companyId) {
requireCapability(manifest, capabilitySet, "agents.read");
const agent = agents.get(agentId);
return isInCompany(agent, companyId) ? agent : null;
},
async pause(agentId, companyId) {
requireCapability(manifest, capabilitySet, "agents.pause");
const cid = requireCompanyId(companyId);
const agent = agents.get(agentId);
if (!isInCompany(agent, cid)) throw new Error(`Agent not found: ${agentId}`);
if (agent!.status === "terminated") throw new Error("Cannot pause terminated agent");
const updated: Agent = { ...agent!, status: "paused", updatedAt: new Date() };
agents.set(agentId, updated);
return updated;
},
async resume(agentId, companyId) {
requireCapability(manifest, capabilitySet, "agents.resume");
const cid = requireCompanyId(companyId);
const agent = agents.get(agentId);
if (!isInCompany(agent, cid)) throw new Error(`Agent not found: ${agentId}`);
if (agent!.status === "terminated") throw new Error("Cannot resume terminated agent");
if (agent!.status === "pending_approval") throw new Error("Pending approval agents cannot be resumed");
const updated: Agent = { ...agent!, status: "idle", updatedAt: new Date() };
agents.set(agentId, updated);
return updated;
},
async invoke(agentId, companyId, opts) {
requireCapability(manifest, capabilitySet, "agents.invoke");
const cid = requireCompanyId(companyId);
const agent = agents.get(agentId);
if (!isInCompany(agent, cid)) throw new Error(`Agent not found: ${agentId}`);
if (
agent!.status === "paused" ||
agent!.status === "terminated" ||
agent!.status === "pending_approval"
) {
throw new Error(`Agent is not invokable in its current state: ${agent!.status}`);
}
return { runId: randomUUID() };
},
async updatePermissions(agentId, companyId, permissions) {
requireCapability(manifest, capabilitySet, "agents.update-permissions");
const cid = requireCompanyId(companyId);
const agent = agents.get(agentId);
if (!isInCompany(agent, cid)) throw new Error(`Agent not found: ${agentId}`);
const updated: Agent = {
...agent!,
permissions: { ...agent!.permissions, ...permissions },
updatedAt: new Date(),
};
agents.set(agentId, updated);
return updated;
},
sessions: {
async create(agentId, companyId, opts) {
requireCapability(manifest, capabilitySet, "agent.sessions.create");
const cid = requireCompanyId(companyId);
const agent = agents.get(agentId);
if (!isInCompany(agent, cid)) throw new Error(`Agent not found: ${agentId}`);
const session: AgentSession = {
sessionId: randomUUID(),
agentId,
companyId: cid,
status: "active",
createdAt: new Date().toISOString(),
};
sessions.set(session.sessionId, session);
return session;
},
async list(agentId, companyId) {
requireCapability(manifest, capabilitySet, "agent.sessions.list");
const cid = requireCompanyId(companyId);
return [...sessions.values()].filter(
(s) => s.agentId === agentId && s.companyId === cid && s.status === "active",
);
},
async sendMessage(sessionId, companyId, opts) {
requireCapability(manifest, capabilitySet, "agent.sessions.send");
const session = sessions.get(sessionId);
if (!session || session.status !== "active") throw new Error(`Session not found or closed: ${sessionId}`);
if (session.companyId !== companyId) throw new Error(`Session not found: ${sessionId}`);
if (opts.onEvent) {
sessionEventCallbacks.set(sessionId, opts.onEvent);
}
return { runId: randomUUID() };
},
async close(sessionId, companyId) {
requireCapability(manifest, capabilitySet, "agent.sessions.close");
const session = sessions.get(sessionId);
if (!session) throw new Error(`Session not found: ${sessionId}`);
if (session.companyId !== companyId) throw new Error(`Session not found: ${sessionId}`);
session.status = "closed";
sessionEventCallbacks.delete(sessionId);
},
},
},
goals: {
async list(input) {
requireCapability(manifest, capabilitySet, "goals.read");
const companyId = requireCompanyId(input?.companyId);
let out = [...goals.values()];
out = out.filter((goal) => goal.companyId === companyId);
if (input?.level) out = out.filter((goal) => goal.level === input.level);
if (input?.status) out = out.filter((goal) => goal.status === input.status);
if (input?.offset) out = out.slice(input.offset);
if (input?.limit) out = out.slice(0, input.limit);
return out;
},
async get(goalId, companyId) {
requireCapability(manifest, capabilitySet, "goals.read");
const goal = goals.get(goalId);
return isInCompany(goal, companyId) ? goal : null;
},
async create(input) {
requireCapability(manifest, capabilitySet, "goals.create");
const now = new Date();
const record: Goal = {
id: randomUUID(),
companyId: input.companyId,
title: input.title,
description: input.description ?? null,
level: input.level ?? "task",
status: input.status ?? "planned",
parentId: input.parentId ?? null,
ownerAgentId: input.ownerAgentId ?? null,
createdAt: now,
updatedAt: now,
};
goals.set(record.id, record);
return record;
},
async update(goalId, patch, companyId) {
requireCapability(manifest, capabilitySet, "goals.update");
const record = goals.get(goalId);
if (!isInCompany(record, companyId)) throw new Error(`Goal not found: ${goalId}`);
const updated: Goal = {
...record,
...patch,
updatedAt: new Date(),
};
goals.set(goalId, updated);
return updated;
},
},
data: {
register(key, handler) {
dataHandlers.set(key, handler);
},
},
actions: {
register(key, handler) {
actionHandlers.set(key, handler);
},
},
streams: (() => {
const channelCompanyMap = new Map<string, string>();
return {
open(channel: string, companyId: string) {
channelCompanyMap.set(channel, companyId);
},
emit(_channel: string, _event: unknown) {
// No-op in test harness — events are not forwarded
},
close(channel: string) {
channelCompanyMap.delete(channel);
},
};
})(),
tools: {
register(name, _decl, fn) {
requireCapability(manifest, capabilitySet, "agent.tools.register");
toolHandlers.set(name, fn);
},
},
metrics: {
async write(name, value, tags) {
requireCapability(manifest, capabilitySet, "metrics.write");
metrics.push({ name, value, tags });
},
},
logger: {
info(message, meta) {
logs.push({ level: "info", message, meta });
},
warn(message, meta) {
logs.push({ level: "warn", message, meta });
},
error(message, meta) {
logs.push({ level: "error", message, meta });
},
debug(message, meta) {
logs.push({ level: "debug", message, meta });
},
},
};
const harness: TestHarness = {
ctx,
seed(input) {
for (const row of input.companies ?? []) companies.set(row.id, row);
for (const row of input.projects ?? []) projects.set(row.id, row);
for (const row of input.issues ?? []) issues.set(row.id, row);
for (const row of input.issueComments ?? []) {
const list = issueComments.get(row.issueId) ?? [];
list.push(row);
issueComments.set(row.issueId, list);
}
for (const row of input.agents ?? []) agents.set(row.id, row);
for (const row of input.goals ?? []) goals.set(row.id, row);
},
setConfig(config) {
currentConfig = { ...config };
},
async emit(eventType, payload, base) {
const event: PluginEvent = {
eventId: base?.eventId ?? randomUUID(),
eventType,
companyId: base?.companyId ?? "test-company",
occurredAt: base?.occurredAt ?? new Date().toISOString(),
actorId: base?.actorId,
actorType: base?.actorType,
entityId: base?.entityId,
entityType: base?.entityType,
payload,
};
for (const handler of events) {
const exactMatch = handler.name === event.eventType;
const wildcardPluginAll = handler.name === "plugin.*" && String(event.eventType).startsWith("plugin.");
const wildcardPluginOne = String(handler.name).endsWith(".*")
&& String(event.eventType).startsWith(String(handler.name).slice(0, -1));
if (!exactMatch && !wildcardPluginAll && !wildcardPluginOne) continue;
if (!allowsEvent(handler.filter, event)) continue;
await handler.fn(event);
}
},
async runJob(jobKey, partial = {}) {
const handler = jobs.get(jobKey);
if (!handler) throw new Error(`No job handler registered for '${jobKey}'`);
await handler({
jobKey,
runId: partial.runId ?? randomUUID(),
trigger: partial.trigger ?? "manual",
scheduledAt: partial.scheduledAt ?? new Date().toISOString(),
});
},
async getData<T = unknown>(key: string, params: Record<string, unknown> = {}) {
const handler = dataHandlers.get(key);
if (!handler) throw new Error(`No data handler registered for '${key}'`);
return await handler(params) as T;
},
async performAction<T = unknown>(key: string, params: Record<string, unknown> = {}) {
const handler = actionHandlers.get(key);
if (!handler) throw new Error(`No action handler registered for '${key}'`);
return await handler(params) as T;
},
async executeTool<T = ToolResult>(name: string, params: unknown, runCtx: Partial<ToolRunContext> = {}) {
const handler = toolHandlers.get(name);
if (!handler) throw new Error(`No tool handler registered for '${name}'`);
const ctxToPass: ToolRunContext = {
agentId: runCtx.agentId ?? "agent-test",
runId: runCtx.runId ?? randomUUID(),
companyId: runCtx.companyId ?? "company-test",
projectId: runCtx.projectId ?? "project-test",
};
return await handler(params, ctxToPass) as T;
},
getState(input) {
return state.get(stateMapKey(input));
},
simulateSessionEvent(sessionId, event) {
const cb = sessionEventCallbacks.get(sessionId);
if (!cb) throw new Error(`No active session event callback for session: ${sessionId}`);
cb({ ...event, sessionId });
},
logs,
activity,
metrics,
};
return harness;
}