apify tool, tools API + automation UI, integrations config, super admin restrictions

- apify tool: TOOL.md definition, index.ts implementation with auto-auth via OFFICER_APIFY_TOKEN, output_path for large datasets
- tools API: /tools routes (list, detail, chat, create, delete) mirroring tasks pattern
- automation UI: tools tab in sidebar, NewTool component, tool detail view
- apify integration: settings page for enterprise API key config, pi-bridge passes env var to containers
- tiktok-trends task: rewritten as agent instructions using apify tool with output_path, scripted report generation for 50KB read limit
- restrict edit/delete of native/global capabilities to Super Admin only (backend + frontend)
- tools authoring guide: TOOLS.md with full spec for TOOL.md frontmatter, index.ts execute signature, patterns

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-02 20:00:45 +00:00
co-authored by Claude Opus 4.6
parent 776738a983
commit bd362dc586
19 changed files with 1059 additions and 149 deletions
@@ -8,6 +8,7 @@ import { NewPipeline } from './NewPipeline';
import { NewCron } from './NewCron';
import { NewService } from './NewService';
import { NewWorkflow } from './NewWorkflow';
import { NewTool } from './NewTool';
export type AutomationSelection = {
kind: string;
@@ -28,6 +29,7 @@ const newComponentMap: Record<string, React.ComponentType<{ selection: NonNullab
Cron: NewCron,
Service: NewService,
Workflow: NewWorkflow,
Tool: NewTool,
};
export const AutomationRightPanel = () => {
@@ -1,4 +1,4 @@
import { Box, Clock, Cpu, GitBranch, ListTodo, Server, Sparkles, Workflow } from 'lucide-react';
import { Box, Clock, Cpu, GitBranch, ListTodo, Server, Sparkles, Workflow, Wrench } from 'lucide-react';
import { usePanelChannel } from 'hooks/usePanelChannel';
import type { AutomationSelection } from './AutomationRightPanel';
@@ -6,6 +6,7 @@ const capabilityItems = [
{ id: 'processes', label: 'Processes', icon: Cpu, kind: 'Process', endpoint: '/processes', queryKey: 'processes' },
{ id: 'tasks', label: 'Tasks', icon: ListTodo, kind: 'Task', endpoint: '/tasks', queryKey: 'tasks' },
{ id: 'skills', label: 'Skills', icon: Sparkles, kind: 'Skill', endpoint: '/skills', queryKey: 'skills' },
{ id: 'tools', label: 'Tools', icon: Wrench, kind: 'Tool', endpoint: '/tools', queryKey: 'tools' },
{ id: 'pipelines', label: 'Pipelines', icon: Workflow, kind: 'Pipeline', endpoint: '/pipelines', queryKey: 'pipelines' },
{ id: 'crons', label: 'Crons', icon: Clock, kind: 'Cron', endpoint: '/crons', queryKey: 'crons' },
{ id: 'services', label: 'Services', icon: Server, kind: 'Service', endpoint: '/services', queryKey: 'services' },
@@ -8,6 +8,7 @@ import { ArrowLeft, Pencil, Play, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { useClient } from 'hooks/useClient';
import { useAuth } from 'hooks/useAuth';
import { usePanelChannel } from 'hooks/usePanelChannel';
import { Card } from '@/components/Card';
import { FrontmatterBlock } from '../CapabilityPage';
@@ -73,6 +74,7 @@ type CapabilityDetailViewProps = {
export const CapabilityDetailView = ({ kind, endpoint, queryKey, dirName, editing }: CapabilityDetailViewProps) => {
const client = useClient();
const qc = useQueryClient();
const { user } = useAuth();
const [selection, setSelection] = usePanelChannel<AutomationSelection>('automation:selected-capability', null);
const [deleteConfirm, setDeleteConfirm] = useState(false);
const [showInputForm, setShowInputForm] = useState(false);
@@ -149,18 +151,22 @@ export const CapabilityDetailView = ({ kind, endpoint, queryKey, dirName, editin
<Play className="h-3.5 w-3.5 text-duck-teal" />
</button>
)}
<button
onClick={toggleEditing}
className={`p-1 rounded hover:bg-duck-dark/10 dark:hover:bg-foreground/10 cursor-pointer transition-colors ${editing ? 'bg-duck-teal/10' : ''}`}
>
<Pencil className={`h-3.5 w-3.5 ${editing ? 'text-duck-teal' : 'text-duck-dark/50 dark:text-foreground/50'}`} />
</button>
<button
onClick={() => setDeleteConfirm(true)}
className="p-1 rounded hover:bg-red-50 cursor-pointer transition-colors"
>
<Trash2 className="h-3.5 w-3.5 text-duck-dark/50 dark:text-foreground/50 hover:text-red-500" />
</button>
{(detail.scope === 'user' || user?.role === 'Super Admin') && (
<>
<button
onClick={toggleEditing}
className={`p-1 rounded hover:bg-duck-dark/10 dark:hover:bg-foreground/10 cursor-pointer transition-colors ${editing ? 'bg-duck-teal/10' : ''}`}
>
<Pencil className={`h-3.5 w-3.5 ${editing ? 'text-duck-teal' : 'text-duck-dark/50 dark:text-foreground/50'}`} />
</button>
<button
onClick={() => setDeleteConfirm(true)}
className="p-1 rounded hover:bg-red-50 cursor-pointer transition-colors"
>
<Trash2 className="h-3.5 w-3.5 text-duck-dark/50 dark:text-foreground/50 hover:text-red-500" />
</button>
</>
)}
</>
)}
</div>
@@ -275,7 +281,7 @@ export const CapabilityDetailView = ({ kind, endpoint, queryKey, dirName, editin
onOpenChange={(open) => {
if (!open) setRunPrompt(null);
}}
task={{ dirName, name: detail.name, description: detail.description ?? '', scope: detail.scope ?? 'user', triggers: [], filePath: detail.filePath }}
task={{ dirName, name: detail.name, description: detail.description ?? '', scope: detail.scope === 'user' ? 'user' : 'global', triggers: [], filePath: detail.filePath }}
promptOverride={runPrompt}
/>
)}
@@ -0,0 +1,94 @@
import { useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { X } from 'lucide-react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { useClient } from 'hooks/useClient';
import { usePanelChannel } from 'hooks/usePanelChannel';
import type { AutomationSelection } from './AutomationRightPanel';
type NewToolProps = {
selection: NonNullable<AutomationSelection>;
};
export const NewTool = ({ selection }: NewToolProps) => {
const client = useClient();
const qc = useQueryClient();
const [, setSelection] = usePanelChannel<AutomationSelection>('automation:selected-capability', null);
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [submitting, setSubmitting] = useState(false);
const handleCreate = async () => {
const trimmed = name.trim();
if (!trimmed) return;
setSubmitting(true);
try {
const res = await client.post<{ name: string; dirName: string }>(selection.endpoint, { name: trimmed });
await qc.invalidateQueries({ queryKey: [selection.queryKey] });
setSelection({
kind: selection.kind,
endpoint: selection.endpoint,
queryKey: selection.queryKey,
dirName: res.dirName,
isNew: true,
editing: true,
description: description.trim() || undefined,
});
} catch {
toast.error('Failed to create tool');
setSubmitting(false);
}
};
return (
<div className="h-full flex flex-col">
<div className="shrink-0 px-4 py-2 border-b border-duck-dark/10 dark:border-foreground/10 bg-background/60 flex items-center gap-2">
<span className="text-sm font-medium text-duck-dark/70 dark:text-foreground/70 flex-1">New Tool</span>
<button
onClick={() => setSelection(null)}
className="p-1 rounded hover:bg-duck-dark/10 dark:hover:bg-foreground/10 cursor-pointer transition-colors"
>
<X className="h-3.5 w-3.5 text-duck-dark/50 dark:text-foreground/50" />
</button>
</div>
<div className="flex-1 overflow-y-auto p-6 flex flex-col gap-4">
<div className="flex flex-col gap-1.5">
<label className="text-sm font-medium text-duck-dark/70 dark:text-foreground/70">Name</label>
<input
value={name}
onChange={(ev) => setName(ev.target.value)}
onKeyDown={(ev) => {
if (ev.key === 'Enter') {
ev.preventDefault();
handleCreate();
}
}}
placeholder="Tool name..."
autoFocus
className="rounded border border-duck-dark/20 dark:border-foreground/20 bg-background px-3 py-2 text-sm text-duck-dark dark:text-foreground placeholder:text-duck-dark/30 dark:placeholder:text-foreground/30 focus:outline-none focus:ring-1 focus:ring-duck-teal/30"
/>
</div>
<div className="flex flex-col gap-1.5">
<label className="text-sm font-medium text-duck-dark/70 dark:text-foreground/70">Description</label>
<textarea
value={description}
onChange={(ev) => setDescription(ev.target.value)}
placeholder="Describe what this tool does..."
rows={4}
className="rounded border border-duck-dark/20 dark:border-foreground/20 bg-background px-3 py-2 text-sm text-duck-dark dark:text-foreground placeholder:text-duck-dark/30 dark:placeholder:text-foreground/30 focus:outline-none focus:ring-1 focus:ring-duck-teal/30 resize-none"
/>
</div>
<div className="flex justify-end">
<Button
onClick={handleCreate}
disabled={!name.trim() || submitting}
className="bg-duck-teal text-duck-yellow hover:bg-duck-teal/90 cursor-pointer"
>
{submitting ? 'Creating...' : 'Create'}
</Button>
</div>
</div>
</div>
);
};
@@ -8,6 +8,7 @@ import { ArrowLeft, Pencil, Plus, Check, X, Trash2, Search, ChevronRight } from
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { useClient } from 'hooks/useClient';
import { useAuth } from 'hooks/useAuth';
import { Card } from '@/components/Card';
import { usePiChat, EmbeddableChat } from 'officerdev';
type CapabilitySummary = {
@@ -249,6 +250,7 @@ export const CapabilityList = ({ kind, endpoint, queryKey, selected, onSelect, o
export const CapabilityPage = ({ kind, endpoint, queryKey }: CapabilityPageProps) => {
const client = useClient();
const qc = useQueryClient();
const { user } = useAuth();
const [selected, setSelected] = useState<string | null>(null);
const [editing, setEditing] = useState(false);
const [isNew, setIsNew] = useState(false);
@@ -330,7 +332,7 @@ export const CapabilityPage = ({ kind, endpoint, queryKey }: CapabilityPageProps
<span className="text-sm font-medium text-duck-dark/70 flex-1">
{detail?.name ?? `Select a ${kind.toLowerCase()}`}
</span>
{detail && (
{detail && (detail.scope === 'user' || user?.role === 'Super Admin') && (
<>
<button
onClick={() => setEditing((e) => !e)}
@@ -0,0 +1,90 @@
import { useState, useEffect } from 'react';
import { toast } from 'sonner';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { useClient } from 'hooks/useClient';
type ApifyConfigData = {
apiToken: string;
};
type ApifyStatus = {
configured: boolean;
};
export const ApifyConfig = () => {
const client = useClient();
const [isLoading, setIsLoading] = useState(true);
const [isSaving, setIsSaving] = useState(false);
const [apiToken, setApiToken] = useState('');
const [status, setStatus] = useState<ApifyStatus | null>(null);
useEffect(() => {
Promise.all([
client.get<ApifyConfigData>('/integrations/apify/config').then((data) => {
if (data?.apiToken) setApiToken(data.apiToken);
}),
client.get<ApifyStatus>('/integrations/apify/status').then(setStatus),
])
.catch(() => {})
.finally(() => setIsLoading(false));
}, []);
const handleSave = async () => {
if (isSaving) return;
setIsSaving(true);
try {
await client.put('/integrations/apify/config', { apiToken: apiToken.trim() });
toast.success('Apify API token saved');
setStatus({ configured: !!apiToken.trim() });
} catch {
toast.error('Failed to save Apify API token');
} finally {
setIsSaving(false);
}
};
if (isLoading) return null;
return (
<div className="grid gap-5">
{status && (
<div className="flex items-center gap-2 rounded-lg border border-duck-dark/10 dark:border-foreground/10 p-3">
<div className={`h-2.5 w-2.5 rounded-full shrink-0 ${status.configured ? 'bg-green-500' : 'bg-duck-dark/20 dark:bg-foreground/20'}`} />
<span className="text-sm text-duck-dark dark:text-foreground">
{status.configured ? 'API token configured' : 'Not configured'}
</span>
</div>
)}
<div className="grid gap-5">
<Label className="grid gap-2">
<span className="text-duck-dark/70 dark:text-foreground/70">API Token</span>
<Input
className="h-11 bg-background/60 border-duck-dark/20 text-duck-dark placeholder:text-duck-dark/40"
type="password"
value={apiToken}
onChange={(ev) => setApiToken(ev.target.value)}
placeholder="apify_api_..."
/>
<span className="text-xs text-duck-dark/40 dark:text-foreground/40">
Get your token at{' '}
<a href="https://console.apify.com/account/integrations" target="_blank" rel="noopener noreferrer" className="text-duck-teal underline">
console.apify.com/account/integrations
</a>
</span>
</Label>
<Button
type="button"
onClick={handleSave}
disabled={isSaving || !apiToken.trim()}
className="w-full h-11 bg-duck-yellow hover:bg-duck-yellow/90 text-duck-teal font-bold transition-all duration-200 hover:scale-105 cursor-pointer disabled:opacity-50 disabled:hover:scale-100"
>
{isSaving ? 'Saving...' : 'Save'}
</Button>
</div>
</div>
);
};
@@ -1,5 +1,5 @@
import { useMemo } from 'react';
import { Puzzle, KeyRound, UserCircle, MessageCircle, Globe } from 'lucide-react';
import { Puzzle, KeyRound, UserCircle, MessageCircle, Globe, Wrench } from 'lucide-react';
import type { LayoutNode, PanelComponents } from 'officerdev';
import { WorkspaceLayout } from 'officerdev';
import { useAuth } from 'hooks/useAuth';
@@ -16,6 +16,7 @@ import { TelegramAccount } from './TelegramAccount';
import { WhatsAppBotConfig } from './WhatsAppBotConfig';
import { WhatsAppAccount } from './WhatsAppAccount';
import { BrowserRelay } from './BrowserRelay';
import { ApifyConfig } from './ApifyConfig';
const GLOBAL_KEY = 'INTEGRATIONS_SETTINGS_SELECTED';
const TAB_KEY = 'INTEGRATIONS_SETTINGS_TAB';
@@ -49,6 +50,13 @@ const enterpriseSections: SettingsSection[] = [
description: 'WhatsApp Web connection',
content: <WhatsAppBotConfig />,
},
{
key: 'apify',
icon: Wrench,
title: 'Apify',
description: 'API token for web scraping actors',
content: <ApifyConfig />,
},
];
const personalSections: SettingsSection[] = [
@@ -33,6 +33,40 @@ integrationsRouter.get('/', async (ctx) => {
return ctx.json([]);
});
// --- Enterprise: Apify config (Super Admin only) ---
type ApifyConfig = { apiToken: string };
export const readApifyConfig = async (): Promise<ApifyConfig | null> => {
const integration = await getServerIntegration('apify');
if (!integration) return null;
const config = integration.config as Record<string, unknown>;
if (!config.apiToken) return null;
return config as unknown as ApifyConfig;
};
integrationsRouter.get('/apify/config', async (ctx) => {
const user = ctx.get('user');
if (user.role !== 'Super Admin') throw FORBIDDEN();
return ctx.json(await readApifyConfig());
});
integrationsRouter.put('/apify/config', async (ctx) => {
const user = ctx.get('user');
if (user.role !== 'Super Admin') throw FORBIDDEN();
const body = ctx.get('body') as { apiToken?: string };
const config = { apiToken: body.apiToken ?? '' };
await upsertServerIntegration('apify', config);
return ctx.json(config);
});
integrationsRouter.get('/apify/status', async (ctx) => {
const config = await readApifyConfig();
return ctx.json({ configured: !!config?.apiToken });
});
// --- Enterprise: Google OAuth config (Super Admin only) ---
integrationsRouter.get('/google/config', async (ctx) => {
+14
View File
@@ -190,6 +190,16 @@ async function ensureGoogleTokenFile(userId: number, email: string): Promise<str
return filePath;
}
async function getApifyToken(): Promise<string> {
try {
const integration = await getServerIntegration('apify');
const config = integration?.config as Record<string, string> | undefined;
return config?.apiToken ?? '';
} catch {
return '';
}
}
async function getBrowserRelayEnv(userId: number): Promise<Record<string, string>> {
const port = getRelayPort();
if (!port) return {};
@@ -265,6 +275,7 @@ export async function spawnPi(
const googleConfigHost = await ensureGoogleConfigFile();
await ensureGoogleTokenFile(sandbox.userId, sandbox.email);
const browserRelayEnv = await getBrowserRelayEnv(sandbox.userId);
const apifyToken = await getApifyToken();
const envFlags = [
'-e', `HOME=${containerHome}`,
@@ -276,6 +287,7 @@ export async function spawnPi(
'-e', `OFFICER_GOOGLE_CONFIG_PATH=/officer/google-oauth.json`,
'-e', `OFFICER_GOOGLE_TOKEN_PATH=/officer/user/integrations/google.json`,
'-e', `OFFICER_EMAIL_DB=/officer/emails.db`,
...(apifyToken ? ['-e', `OFFICER_APIFY_TOKEN=${apifyToken}`] : []),
...Object.entries(browserRelayEnv).flatMap(([k, v]) => ['-e', `${k}=${v}`]),
];
@@ -321,6 +333,7 @@ export async function spawnPi(
const googleConfigPath = await ensureGoogleConfigFile();
const googleTokenPath = await ensureGoogleTokenFile(userId, email);
const browserRelayEnv = await getBrowserRelayEnv(userId);
const apifyTokenLocal = await getApifyToken();
proc = Bun.spawn(args, {
cwd,
@@ -339,6 +352,7 @@ export async function spawnPi(
OFFICER_GOOGLE_CONFIG_PATH: googleConfigPath,
OFFICER_GOOGLE_TOKEN_PATH: googleTokenPath,
OFFICER_EMAIL_DB: join(DATA_PATH, email, 'emails.db'),
...(apifyTokenLocal ? { OFFICER_APIFY_TOKEN: apifyTokenLocal } : {}),
...browserRelayEnv,
},
});
+1 -1
View File
@@ -54,7 +54,7 @@ function resolveFile(name: string, native: Map<string, string>, global: Map<stri
}
function isPrivileged(role: string) {
return role === 'Admin' || role === 'Owner' || role === 'Super Admin';
return role === 'Super Admin';
}
export const processesRouter = createRouter();
+1 -1
View File
@@ -41,7 +41,7 @@ function mergeConfig(native: Record<string, string>, global: Record<string, stri
}
function isPrivileged(role: string) {
return role === 'Admin' || role === 'Owner' || role === 'Super Admin';
return role === 'Super Admin';
}
export async function readResourceConfig(name: string): Promise<Record<string, string>> {
+1 -1
View File
@@ -41,7 +41,7 @@ export async function readSkillDirs(dir: string): Promise<Map<string, string>> {
type Scope = 'native' | 'global' | 'user';
function isPrivileged(role: string) {
return role === 'Admin' || role === 'Owner' || role === 'Super Admin';
return role === 'Super Admin';
}
function resolveScope(dirName: string, native: Map<string, string>, global: Map<string, string>, user: Map<string, string>): Scope {
+1 -1
View File
@@ -73,7 +73,7 @@ function resolveFile(name: string, native: Map<string, string>, global: Map<stri
}
function isPrivileged(role: string) {
return role === 'Admin' || role === 'Owner' || role === 'Super Admin';
return role === 'Super Admin';
}
export const tasksRouter = createRouter();
+217
View File
@@ -0,0 +1,217 @@
import { createRouter } from '../../create-router';
import { readdir, mkdir, rm } from 'node:fs/promises';
import { join, dirname } from 'node:path';
import { getNativeToolsDir, getGlobalToolsDir, getUserToolsDir } from '../../data-path';
type Frontmatter = {
name: string;
description: string;
};
export function parseFrontmatter(raw: string): { frontmatter: Frontmatter; body: string; rawYaml: string } {
const match = raw.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
if (!match) return { frontmatter: { name: '', description: '' }, body: raw, rawYaml: '' };
const yaml = match[1]!;
const body = match[2]!;
const name = yaml.match(/^name:\s*(.+)$/m)?.[1]?.trim() ?? '';
const description = yaml.match(/^description:\s*(.+)$/m)?.[1]?.trim() ?? '';
return { frontmatter: { name, description }, body, rawYaml: yaml };
}
export async function readToolDirs(dir: string): Promise<Map<string, string>> {
const result = new Map<string, string>();
try {
const entries = await readdir(dir, { withFileTypes: true });
for (const entry of entries) {
if (!entry.isDirectory()) continue;
const toolFile = join(dir, entry.name, 'TOOL.md');
if (await Bun.file(toolFile).exists()) {
result.set(entry.name, toolFile);
}
}
} catch {
// directory doesn't exist yet
}
return result;
}
type Scope = 'native' | 'global' | 'user';
function resolveScope(dirName: string, native: Map<string, string>, global: Map<string, string>, user: Map<string, string>): Scope {
if (user.has(dirName)) return 'user';
if (global.has(dirName)) return 'global';
return 'native';
}
function resolveFile(name: string, native: Map<string, string>, global: Map<string, string>, user: Map<string, string>): { filePath: string; scope: Scope } | null {
if (user.has(name)) return { filePath: user.get(name)!, scope: 'user' };
if (global.has(name)) return { filePath: global.get(name)!, scope: 'global' };
if (native.has(name)) return { filePath: native.get(name)!, scope: 'native' };
return null;
}
function isPrivileged(role: string) {
return role === 'Super Admin';
}
export const toolsRouter = createRouter();
toolsRouter.get('/', async (ctx) => {
const user = ctx.get('user');
const nativeTools = await readToolDirs(getNativeToolsDir());
const globalTools = await readToolDirs(getGlobalToolsDir());
const userTools = await readToolDirs(getUserToolsDir(user.email));
const merged = new Map(nativeTools);
for (const [name, path] of globalTools) merged.set(name, path);
for (const [name, path] of userTools) merged.set(name, path);
const tools = await Promise.all(
Array.from(merged.entries()).map(async ([dirName, filePath]) => {
const raw = await Bun.file(filePath).text();
const { frontmatter } = parseFrontmatter(raw);
const scope = resolveScope(dirName, nativeTools, globalTools, userTools);
return {
dirName,
name: frontmatter.name || dirName,
description: frontmatter.description,
scope,
filePath,
};
}),
);
return ctx.json(tools);
});
toolsRouter.get('/:name', async (ctx) => {
const user = ctx.get('user');
const name = ctx.req.param('name');
const nativeTools = await readToolDirs(getNativeToolsDir());
const globalTools = await readToolDirs(getGlobalToolsDir());
const userTools = await readToolDirs(getUserToolsDir(user.email));
const resolved = resolveFile(name, nativeTools, globalTools, userTools);
if (!resolved) return ctx.text('Not found', 404);
const raw = await Bun.file(resolved.filePath).text();
const { frontmatter, body, rawYaml } = parseFrontmatter(raw);
const chatMeta = join(dirname(resolved.filePath), 'chat', 'meta.json');
const chatSessionId = await Bun.file(chatMeta).json().then((m: { id: string }) => m.id).catch(() => null);
return ctx.json({
name: frontmatter.name || name,
description: frontmatter.description,
scope: resolved.scope,
body,
rawFrontmatter: rawYaml,
filePath: resolved.filePath,
chatSessionId,
});
});
toolsRouter.get('/:name/chat', async (ctx) => {
const user = ctx.get('user');
const name = ctx.req.param('name');
const nativeTools = await readToolDirs(getNativeToolsDir());
const globalTools = await readToolDirs(getGlobalToolsDir());
const userTools = await readToolDirs(getUserToolsDir(user.email));
const resolved = resolveFile(name, nativeTools, globalTools, userTools);
if (!resolved) return ctx.text('Not found', 404);
const chatDir = join(dirname(resolved.filePath), 'chat');
const sessionId = await Bun.file(join(chatDir, 'meta.json')).json().then((m: { id: string }) => m.id).catch(() => null);
const messages = await Bun.file(join(chatDir, 'messages.json')).json().catch(() => []);
return ctx.json({ sessionId, messages });
});
toolsRouter.put('/:name/chat', async (ctx) => {
const user = ctx.get('user');
const name = ctx.req.param('name');
const nativeTools = await readToolDirs(getNativeToolsDir());
const globalTools = await readToolDirs(getGlobalToolsDir());
const userTools = await readToolDirs(getUserToolsDir(user.email));
const resolved = resolveFile(name, nativeTools, globalTools, userTools);
if (!resolved) return ctx.text('Not found', 404);
if (resolved.scope !== 'user' && !isPrivileged(user.role)) return ctx.text('Forbidden', 403);
const chatDir = join(dirname(resolved.filePath), 'chat');
const { sessionId, messages } = await ctx.req.json<{ sessionId: string; messages: unknown[] }>();
await mkdir(chatDir, { recursive: true });
await Bun.write(join(chatDir, 'messages.json'), JSON.stringify(messages));
if (sessionId) await Bun.write(join(chatDir, 'meta.json'), JSON.stringify({ id: sessionId }));
return ctx.json({ ok: true });
});
toolsRouter.delete('/:name/chat', async (ctx) => {
const user = ctx.get('user');
const name = ctx.req.param('name');
const nativeTools = await readToolDirs(getNativeToolsDir());
const globalTools = await readToolDirs(getGlobalToolsDir());
const userTools = await readToolDirs(getUserToolsDir(user.email));
const resolved = resolveFile(name, nativeTools, globalTools, userTools);
if (!resolved) return ctx.text('Not found', 404);
if (resolved.scope !== 'user' && !isPrivileged(user.role)) return ctx.text('Forbidden', 403);
const chatDir = join(dirname(resolved.filePath), 'chat');
await rm(chatDir, { recursive: true, force: true });
return ctx.json({ ok: true });
});
toolsRouter.post('/', async (ctx) => {
const user = ctx.get('user');
const { name } = await ctx.req.json<{ name: string }>();
if (!name?.trim()) return ctx.text('Name is required', 400);
const dirName = name.trim().toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '');
if (!dirName) return ctx.text('Invalid name', 400);
const targetDir = isPrivileged(user.role) ? getGlobalToolsDir() : getUserToolsDir(user.email);
const scope: Scope = isPrivileged(user.role) ? 'global' : 'user';
const dir = join(targetDir, dirName);
const filePath = join(dir, 'TOOL.md');
if (await Bun.file(filePath).exists()) {
return ctx.text('Tool already exists', 409);
}
await mkdir(dir, { recursive: true });
await Bun.write(filePath, `---\nname: ${name.trim()}\ndescription: \n---\n`);
return ctx.json({ name: name.trim(), dirName, filePath, scope });
});
toolsRouter.delete('/:name', async (ctx) => {
const user = ctx.get('user');
const name = ctx.req.param('name');
const nativeTools = await readToolDirs(getNativeToolsDir());
const globalTools = await readToolDirs(getGlobalToolsDir());
const userTools = await readToolDirs(getUserToolsDir(user.email));
const resolved = resolveFile(name, nativeTools, globalTools, userTools);
if (!resolved) return ctx.text('Not found', 404);
if (resolved.scope !== 'user' && !isPrivileged(user.role)) return ctx.text('Forbidden', 403);
await rm(dirname(resolved.filePath), { recursive: true });
return ctx.json({ ok: true });
});
+2
View File
@@ -10,6 +10,7 @@ import { usersRouter } from './api/users/users-router';
import { plansRouter } from './api/plans/plans';
import { skillsRouter } from './api/skills/skills';
import { tasksRouter } from './api/tasks/tasks';
import { toolsRouter } from './api/tools/tools';
import { processesRouter } from './api/processes/processes';
import { sessionsRouter } from './api/sessions/sessions';
import { scrapeRouter } from './api/scrape/scrape';
@@ -71,6 +72,7 @@ protectedRouter.route('/users', usersRouter);
protectedRouter.route('/plans', plansRouter);
protectedRouter.route('/skills', skillsRouter);
protectedRouter.route('/tasks', tasksRouter);
protectedRouter.route('/tools', toolsRouter);
protectedRouter.route('/processes', processesRouter);
protectedRouter.route('/', sessionsRouter);
protectedRouter.route('/scrape', scrapeRouter);