script-mode task execution — database-backed tasks with direct script runner

Tasks now live in the database (mode: script or agentic). Script-mode tasks
bypass the agent entirely — the implementation is materialized to a temp file
and executed directly, with stdout/stderr streamed to the UI via WebSocket.

Includes convert-to-mp3 as the first native script task.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-08 16:07:59 +00:00
co-authored by Claude Opus 4.6
parent 1159978187
commit f32f427972
15 changed files with 3238 additions and 209 deletions
+35
View File
@@ -0,0 +1,35 @@
---
name: Convert To MP3
description: Convert audio files to MP3 320kbps, preserving metadata.
version: 1
mode: script
language: bash
triggers:
- type: file
extensions:
- flac
- wav
- ogg
- wma
- aac
- m4a
- opus
- aiff
- aif
- ape
- wv
- alac
- dsf
- dff
- type: directory
inputs:
file_path:
type: string
description: Path to an audio file or directory to convert.
args: [file_path]
---
# Convert To MP3
Convert audio files to MP3 320kbps using ffmpeg, preserving metadata.
Supports single file conversion and batch directory conversion.
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env bash
set -euo pipefail
# Accepts path as $1 or $INPUT_FILE_PATH
TARGET="${1:-${INPUT_FILE_PATH:-}}"
if [[ -z "$TARGET" ]]; then
echo "Error: No file or directory path provided" >&2
exit 1
fi
if [[ ! -e "$TARGET" ]]; then
echo "Error: Path does not exist: $TARGET" >&2
exit 1
fi
convert_file() {
local input="$1"
local ext="${input##*.}"
local dir
dir="$(dirname "$input")"
local base
base="$(basename "$input" ".$ext")"
local output="$dir/$base.mp3"
if [[ "${ext,,}" == "mp3" ]]; then
echo "Skipping (already MP3): $input"
return 0
fi
if [[ -f "$output" ]]; then
echo "Skipping (output exists): $output"
return 0
fi
echo "Converting: $input$output"
ffmpeg -i "$input" -codec:a libmp3lame -b:a 320k -map_metadata 0 -id3v2_version 3 -y "$output" 2>/dev/null
if [[ $? -eq 0 ]]; then
echo " ✓ Done"
else
echo " ✗ Failed" >&2
return 1
fi
}
AUDIO_EXTS="flac|wav|ogg|wma|aac|m4a|opus|aiff|aif|ape|wv|alac|dsf|dff"
converted=0
failed=0
if [[ -f "$TARGET" ]]; then
if convert_file "$TARGET"; then
converted=$((converted + 1))
else
failed=$((failed + 1))
fi
elif [[ -d "$TARGET" ]]; then
while IFS= read -r -d '' file; do
if convert_file "$file"; then
converted=$((converted + 1))
else
failed=$((failed + 1))
fi
done < <(find "$TARGET" -type f -regextype posix-extended -iregex ".*\.($AUDIO_EXTS)" -print0 | sort -z)
if [[ $converted -eq 0 && $failed -eq 0 ]]; then
echo "No audio files found in: $TARGET"
exit 0
fi
else
echo "Error: Not a file or directory: $TARGET" >&2
exit 1
fi
echo ""
echo "Summary: $converted converted, $failed failed"
@@ -0,0 +1,4 @@
ALTER TABLE "tasks" ADD COLUMN "mode" text DEFAULT 'agentic' NOT NULL;--> statement-breakpoint
ALTER TABLE "tasks" ADD COLUMN "language" text;--> statement-breakpoint
ALTER TABLE "tasks" ADD COLUMN "implementation" text;--> statement-breakpoint
ALTER TABLE "tasks" ADD COLUMN "args" jsonb;
File diff suppressed because it is too large Load Diff
@@ -15,6 +15,13 @@
"when": 1772799835768, "when": 1772799835768,
"tag": "0001_freezing_carmella_unuscione", "tag": "0001_freezing_carmella_unuscione",
"breakpoints": true "breakpoints": true
},
{
"idx": 2,
"version": "7",
"when": 1772985087180,
"tag": "0002_cute_doorman",
"breakpoints": true
} }
] ]
} }
+166
View File
@@ -0,0 +1,166 @@
/**
* Seed native tasks into the database.
* Run: bun src/databases/officer_db/seed-tasks.ts
*/
import { eq, and } from 'drizzle-orm';
import { db } from './src/db';
import { tasks } from './src/schema/agent-items';
import { readdirSync, readFileSync, existsSync } from 'node:fs';
import { join, resolve } from 'node:path';
const SEED_TASKS_DIR = resolve(import.meta.dir, '../../../seed/tasks');
type TriggerConfig = { type: 'file'; extensions: string[] } | { type: 'directory' };
function parseFrontmatter(content: string) {
const match = content.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
if (!match) return { meta: {} as Record<string, unknown>, body: content };
const yaml = match[1]!;
const body = match[2]!;
const meta: Record<string, unknown> = {};
meta.name = yaml.match(/^name:\s*(.+)$/m)?.[1]?.trim() ?? '';
meta.description = yaml.match(/^description:\s*(.+)$/m)?.[1]?.trim() ?? '';
meta.mode = yaml.match(/^mode:\s*(.+)$/m)?.[1]?.trim() ?? 'agentic';
meta.language = yaml.match(/^language:\s*(.+)$/m)?.[1]?.trim() ?? undefined;
meta.version = parseInt(yaml.match(/^version:\s*(.+)$/m)?.[1]?.trim() ?? '1', 10);
// Parse args
const argsMatch = yaml.match(/^args:\s*\[([^\]]*)\]/m);
meta.args = argsMatch ? argsMatch[1]!.split(',').map((a) => a.trim()).filter(Boolean) : undefined;
// Parse triggers
const triggers: TriggerConfig[] = [];
const triggerMatch = yaml.match(/^triggers?:\s*\n((?:[ \t]+.+\n?)*)/m);
if (triggerMatch) {
const items = triggerMatch[1]!.split(/(?=^\s+-\s*type:)/m);
for (const item of items) {
const type = item.match(/type:\s*(.+)/)?.[1]?.trim();
if (type === 'directory') {
triggers.push({ type: 'directory' });
} else if (type === 'file') {
const extBlock = item.match(/extensions:\s*\n((?:\s+-\s*.+\n?)*)/);
const extensions = extBlock ? [...extBlock[1]!.matchAll(/^\s+-\s*(.+)$/gm)].map((m) => m[1]!.trim()) : [];
if (extensions.length > 0) triggers.push({ type: 'file', extensions });
}
}
}
meta.trigger = triggers.length > 0 ? triggers : undefined;
// Parse inputs (simplified — store as-is for now)
const inputsMatch = yaml.match(/^inputs:\s*\n((?:[ \t]+.+\n?)*)/m);
if (inputsMatch) {
const inputBlock = inputsMatch[1]!;
const inputEntries: Record<string, Record<string, string>> = {};
let currentInput: string | null = null;
for (const line of inputBlock.split('\n')) {
const topMatch = line.match(/^\s{2}(\w[\w_-]*):\s*$/);
if (topMatch) {
currentInput = topMatch[1]!;
inputEntries[currentInput] = {};
continue;
}
const propMatch = line.match(/^\s{4}(\w[\w_-]*):\s*(.+)$/);
if (propMatch && currentInput) {
inputEntries[currentInput]![propMatch[1]!] = propMatch[2]!.trim();
}
}
if (Object.keys(inputEntries).length > 0) {
meta.inputs = inputEntries;
}
}
return { meta, body };
}
async function seedTasks() {
if (!existsSync(SEED_TASKS_DIR)) {
console.log('No seed tasks directory found');
return;
}
const entries = readdirSync(SEED_TASKS_DIR, { withFileTypes: true });
for (const entry of entries) {
if (!entry.isDirectory()) continue;
const taskDir = join(SEED_TASKS_DIR, entry.name);
const taskMdPath = join(taskDir, 'TASK.md');
if (!existsSync(taskMdPath)) continue;
const content = readFileSync(taskMdPath, 'utf-8');
const { meta, body } = parseFrontmatter(content);
// Find implementation file
let implementation: string | null = null;
const lang = meta.language as string | undefined;
const implCandidates = [
{ file: 'run.sh', lang: 'bash' },
{ file: 'index.ts', lang: 'typescript' },
{ file: 'run.py', lang: 'python' },
{ file: 'index.js', lang: 'javascript' },
];
for (const c of implCandidates) {
const path = join(taskDir, c.file);
if (existsSync(path)) {
implementation = readFileSync(path, 'utf-8');
break;
}
}
const values = {
scope: 'native' as const,
userId: null,
dirName: entry.name,
name: (meta.name as string) || entry.name,
description: (meta.description as string) || null,
body: body || null,
version: (meta.version as number) || 1,
mode: (meta.mode as string) || 'agentic',
language: (meta.language as string) || null,
implementation,
args: (meta.args as string[]) || null,
trigger: (meta.trigger as TriggerConfig[]) || null,
inputs: (meta.inputs as Record<string, unknown>) || null,
};
// Upsert: check by dirName + scope since unique constraint doesn't work with NULL userId
const existing = await db
.select({ id: tasks.id })
.from(tasks)
.where(and(eq(tasks.dirName, values.dirName), eq(tasks.scope, 'native')))
.limit(1);
if (existing.length > 0) {
await db
.update(tasks)
.set({
name: values.name,
description: values.description,
body: values.body,
version: values.version,
mode: values.mode,
language: values.language,
implementation: values.implementation,
args: values.args,
trigger: values.trigger,
inputs: values.inputs,
updatedAt: new Date(),
})
.where(eq(tasks.id, existing[0]!.id));
} else {
await db.insert(tasks).values(values);
}
console.log(`Seeded: ${entry.name} (${meta.mode}/${meta.language})`);
}
console.log('Done seeding tasks');
process.exit(0);
}
seedTasks().catch((err) => {
console.error('Seed failed:', err);
process.exit(1);
});
+9
View File
@@ -72,5 +72,14 @@ export {
deleteSavedSession, deleteSavedSession,
} from './queries/saved-sessions'; } from './queries/saved-sessions';
export {
getTasksForUser,
getTaskById,
getTaskByDirName,
createTask,
updateTask,
deleteTask,
} from './queries/tasks';
export { db } from './db'; export { db } from './db';
export * as schema from './schema'; export * as schema from './schema';
@@ -0,0 +1,74 @@
import { eq, or, and, isNull, sql } from 'drizzle-orm';
import { db } from '../db';
import { tasks } from '../schema/agent-items';
export async function getTasksForUser(userId: number) {
return db
.select({
id: tasks.id,
dirName: tasks.dirName,
name: tasks.name,
description: tasks.description,
mode: tasks.mode,
language: tasks.language,
version: tasks.version,
scope: tasks.scope,
trigger: tasks.trigger,
userId: tasks.userId,
})
.from(tasks)
.where(
or(
eq(tasks.scope, 'native'),
eq(tasks.scope, 'global'),
and(eq(tasks.scope, 'user'), eq(tasks.userId, userId)),
),
)
.orderBy(tasks.name);
}
export async function getTaskById(id: number) {
const rows = await db.select().from(tasks).where(eq(tasks.id, id)).limit(1);
return rows[0] ?? null;
}
export async function getTaskByDirName(dirName: string, userId: number) {
// User scope takes priority over global, which takes priority over native
const rows = await db
.select()
.from(tasks)
.where(
and(
eq(tasks.dirName, dirName),
or(
eq(tasks.scope, 'native'),
eq(tasks.scope, 'global'),
and(eq(tasks.scope, 'user'), eq(tasks.userId, userId)),
),
),
)
.orderBy(sql`CASE scope WHEN 'user' THEN 0 WHEN 'global' THEN 1 ELSE 2 END`)
.limit(1);
return rows[0] ?? null;
}
type TaskInsert = typeof tasks.$inferInsert;
export async function createTask(data: TaskInsert) {
const rows = await db.insert(tasks).values(data).returning();
return rows[0]!;
}
export async function updateTask(id: number, data: Partial<TaskInsert>) {
const rows = await db
.update(tasks)
.set({ ...data, updatedAt: new Date() })
.where(eq(tasks.id, id))
.returning();
return rows[0] ?? null;
}
export async function deleteTask(id: number) {
await db.delete(tasks).where(eq(tasks.id, id));
}
@@ -19,6 +19,10 @@ export const tasks = pgTable(
description: text('description'), description: text('description'),
body: text('body'), body: text('body'),
version: integer('version').notNull().default(1), version: integer('version').notNull().default(1),
mode: text('mode').notNull().default('agentic'),
language: text('language'),
implementation: text('implementation'),
args: jsonb('args').$type<string[]>(),
tags: jsonb('tags').$type<string[]>(), tags: jsonb('tags').$type<string[]>(),
tools: jsonb('tools').$type<string[]>(), tools: jsonb('tools').$type<string[]>(),
skills: jsonb('skills').$type<string[]>(), skills: jsonb('skills').$type<string[]>(),
+5 -2
View File
@@ -6,6 +6,7 @@ import { verify } from './servers/jwt';
import { isTokenBlacklisted } from 'officerdb'; import { isTokenBlacklisted } from 'officerdb';
import { terminalWebsocket } from './servers/api/terminal/websocket'; import { terminalWebsocket } from './servers/api/terminal/websocket';
import { piWebsocket } from './servers/api/pi/websocket'; import { piWebsocket } from './servers/api/pi/websocket';
import { taskRunnerWebsocket } from './servers/api/tasks/task-executor';
import { cliampWebsocket } from './servers/api/cliamp/websocket'; import { cliampWebsocket } from './servers/api/cliamp/websocket';
import { cliampAudioWebsocket } from './servers/api/cliamp/audio-ws'; import { cliampAudioWebsocket } from './servers/api/cliamp/audio-ws';
import { desktopWebsocket } from './servers/api/desktop/websocket'; import { desktopWebsocket } from './servers/api/desktop/websocket';
@@ -23,7 +24,7 @@ type WSData = {
email: string; email: string;
username: string; username: string;
role: string; role: string;
provider: 'terminal' | 'pi' | 'dev-server' | 'cliamp' | 'cliamp-audio' | 'desktop' | 'sidecar'; provider: 'terminal' | 'pi' | 'task-runner' | 'dev-server' | 'cliamp' | 'cliamp-audio' | 'desktop' | 'sidecar';
sandboxed: boolean; sandboxed: boolean;
sessionId?: string; sessionId?: string;
cwd?: string; cwd?: string;
@@ -116,6 +117,7 @@ async function handleSidecarQueueCommand(ws: ServerWebSocket<WSData>, msg: Recor
const handlers: Record<string, any> = { const handlers: Record<string, any> = {
terminal: terminalWebsocket, terminal: terminalWebsocket,
pi: piWebsocket, pi: piWebsocket,
'task-runner': taskRunnerWebsocket,
cliamp: cliampWebsocket, cliamp: cliampWebsocket,
'cliamp-audio': cliampAudioWebsocket, 'cliamp-audio': cliampAudioWebsocket,
desktop: desktopWebsocket, desktop: desktopWebsocket,
@@ -187,7 +189,7 @@ const devServerWebsocket = {
}; };
handlers['dev-server'] = devServerWebsocket; handlers['dev-server'] = devServerWebsocket;
async function upgradeWs(req: Request, server: any, provider: 'terminal' | 'pi' | 'cliamp' | 'cliamp-audio' | 'desktop') { async function upgradeWs(req: Request, server: any, provider: 'terminal' | 'pi' | 'task-runner' | 'cliamp' | 'cliamp-audio' | 'desktop') {
const token = new URL(req.url).searchParams.get('token'); const token = new URL(req.url).searchParams.get('token');
if (!token) return new Response('Unauthorized', { status: 401 }); if (!token) return new Response('Unauthorized', { status: 401 });
@@ -271,6 +273,7 @@ const server = serve({
}); });
if (!ok) return new Response('Upgrade failed', { status: 500 }); if (!ok) return new Response('Upgrade failed', { status: 500 });
}, },
'/api/tasks/run/ws': (req, server) => upgradeWs(req, server, 'task-runner'),
'/api/terminal/ws': (req, server) => upgradeWs(req, server, 'terminal'), '/api/terminal/ws': (req, server) => upgradeWs(req, server, 'terminal'),
'/api/pi/chat/ws': (req, server) => upgradeWs(req, server, 'pi'), '/api/pi/chat/ws': (req, server) => upgradeWs(req, server, 'pi'),
'/api/cliamp/ws': (req, server) => upgradeWs(req, server, 'cliamp'), '/api/cliamp/ws': (req, server) => upgradeWs(req, server, 'cliamp'),
+255
View File
@@ -0,0 +1,255 @@
import type { ServerWebSocket } from 'bun';
import { join } from 'node:path';
import { mkdirSync, writeFileSync, chmodSync, rmSync } from 'node:fs';
import { getTaskByDirName } from 'officerdb';
import { getHomeDirForRole, DATA_PATH } from '../../data-path';
import { buildSandboxPrefix, buildRunuserSuffix } from '../../sidecar/sandbox';
type WSData = {
userId: number;
email: string;
username: string;
role: string;
sandboxed: boolean;
};
type RunMessage = {
type: 'run';
taskDirName: string;
inputs: Record<string, string>;
cwd?: string;
};
type StopMessage = {
type: 'stop';
};
type ClientMessage = RunMessage | StopMessage;
type OutMessage =
| { type: 'started'; taskName: string }
| { type: 'stdout'; data: string }
| { type: 'stderr'; data: string }
| { type: 'exit'; code: number }
| { type: 'error'; message: string };
// Active processes per WebSocket
const activeProcs = new WeakMap<ServerWebSocket<WSData>, { proc: ReturnType<typeof Bun.spawn>; kill: () => void }>();
import { tmpdir } from 'node:os';
function send(ws: ServerWebSocket<WSData>, msg: OutMessage) {
if (ws.readyState === 1) ws.send(JSON.stringify(msg));
}
function getRunner(language: string): string[] {
switch (language) {
case 'bash': return ['bash'];
case 'python': return ['python3'];
case 'typescript': return ['bun', 'run'];
case 'javascript': return ['node'];
default: return ['bash'];
}
}
function getFileName(language: string): string {
switch (language) {
case 'bash': return 'run.sh';
case 'python': return 'run.py';
case 'typescript': return 'index.ts';
case 'javascript': return 'index.js';
default: return 'run.sh';
}
}
// Write implementation to a temp file for execution, cleaned up after
function materializeScript(language: string, implementation: string): string {
const dir = join(tmpdir(), `officer-task-${Date.now()}-${Math.random().toString(36).slice(2)}`);
mkdirSync(dir, { recursive: true });
const fileName = getFileName(language);
const filePath = join(dir, fileName);
writeFileSync(filePath, implementation);
chmodSync(filePath, 0o755);
return filePath;
}
function buildInputEnv(inputs: Record<string, string>): Record<string, string> {
const env: Record<string, string> = {};
for (const [key, value] of Object.entries(inputs)) {
env[`INPUT_${key.toUpperCase()}`] = value;
}
return env;
}
function buildArgs(inputs: Record<string, string>, argsOrder?: string[] | null): string[] {
if (!argsOrder || argsOrder.length === 0) return [];
return argsOrder.map((name) => inputs[name] ?? '');
}
async function handleRun(ws: ServerWebSocket<WSData>, msg: RunMessage) {
const { email, role, sandboxed, userId } = ws.data;
// Resolve task from database
const task = await getTaskByDirName(msg.taskDirName, userId);
if (!task) {
send(ws, { type: 'error', message: `Task not found: ${msg.taskDirName}` });
return;
}
if (task.mode !== 'script') {
send(ws, { type: 'error', message: 'Task is not a script-mode task' });
return;
}
if (!task.implementation) {
send(ws, { type: 'error', message: `Task ${msg.taskDirName} has no implementation` });
return;
}
const language = task.language ?? 'bash';
// Write script to temp dir for execution
const scriptPath = materializeScript(language, task.implementation);
// Build env vars from inputs
const inputEnv = buildInputEnv(msg.inputs);
// Build positional args
const positionalArgs = buildArgs(msg.inputs, task.args);
// Build the command
const runner = getRunner(language);
const cmd = [...runner, scriptPath, ...positionalArgs];
// Resolve cwd
const homeDir = getHomeDirForRole(email, role);
const cwd = msg.cwd ?? homeDir;
let spawnCmd: string[];
let spawnEnv: Record<string, string>;
let spawnCwd: string;
if (sandboxed) {
const prefix = buildSandboxPrefix(email);
const suffix = buildRunuserSuffix();
// Translate paths in inputs and args: DATA_PATH/{email}/... → /data/...
const userDataPrefix = join(DATA_PATH, email);
const translatePath = (v: string) => v.startsWith(userDataPrefix) ? '/data' + v.slice(userDataPrefix.length) : v;
const envArgs: string[] = [];
for (const [key, value] of Object.entries(inputEnv)) {
envArgs.push('--setenv', key, translatePath(value));
}
// Translate positional args too
const sandboxCmd = cmd.map((arg) => translatePath(arg));
// Script is in /tmp which is a tmpfs inside bwrap — need to bind-mount the host tmp dir
const scriptDir = join(scriptPath, '..');
const extraMounts = ['--ro-bind', scriptDir, scriptDir];
spawnCmd = [...prefix, ...extraMounts, ...envArgs, ...suffix, ...sandboxCmd];
spawnEnv = {};
spawnCwd = '/';
} else {
spawnCmd = cmd;
spawnEnv = { ...process.env as Record<string, string>, ...inputEnv };
spawnCwd = cwd;
}
const cleanup = () => {
try { rmSync(join(scriptPath, '..'), { recursive: true, force: true }); } catch { /* best effort */ }
};
send(ws, { type: 'started', taskName: task.name });
try {
const proc = Bun.spawn(spawnCmd, {
cwd: spawnCwd,
env: spawnEnv,
stdout: 'pipe',
stderr: 'pipe',
});
activeProcs.set(ws, {
proc,
kill: () => {
try { proc.kill(); } catch { /* already dead */ }
},
});
const stdoutReader = proc.stdout.getReader();
const stderrReader = proc.stderr.getReader();
const decoder = new TextDecoder();
const readStream = async (reader: ReadableStreamDefaultReader<Uint8Array>, type: 'stdout' | 'stderr') => {
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
send(ws, { type, data: decoder.decode(value) });
}
} catch {
// stream closed
}
};
const [, , exitCode] = await Promise.all([
readStream(stdoutReader, 'stdout'),
readStream(stderrReader, 'stderr'),
proc.exited,
]);
activeProcs.delete(ws);
cleanup();
send(ws, { type: 'exit', code: exitCode });
} catch (err) {
activeProcs.delete(ws);
cleanup();
send(ws, { type: 'error', message: `Failed to spawn: ${err instanceof Error ? err.message : String(err)}` });
}
}
export function open(_ws: ServerWebSocket<WSData>) {
// nothing to do
}
export function message(ws: ServerWebSocket<WSData>, raw: string | Buffer) {
const data = typeof raw === 'string' ? raw : raw.toString();
try {
const msg = JSON.parse(data) as ClientMessage;
if (msg.type === 'run') {
handleRun(ws, msg);
} else if (msg.type === 'stop') {
const active = activeProcs.get(ws);
if (active) {
active.kill();
activeProcs.delete(ws);
send(ws, { type: 'exit', code: -1 });
}
}
} catch {
send(ws, { type: 'error', message: 'Failed to parse message' });
}
}
export function close(ws: ServerWebSocket<WSData>) {
const active = activeProcs.get(ws);
if (active) {
active.kill();
activeProcs.delete(ws);
}
}
export const taskRunnerWebsocket = {
open,
message,
close,
drain() {},
};
+49 -194
View File
@@ -1,77 +1,8 @@
import { createRouter } from '../../create-router'; import { createRouter } from '../../create-router';
import { readdir, mkdir, rm } from 'node:fs/promises'; import { getTasksForUser, getTaskByDirName, getTaskById, createTask, updateTask, deleteTask } from 'officerdb';
import { join, dirname } from 'node:path';
import { getNativeTasksDir, getGlobalTasksDir, getUserTasksDir } from '../../data-path';
type TriggerConfig = { type: 'file'; extensions: string[] } | { type: 'directory' }; type TriggerConfig = { type: 'file'; extensions: string[] } | { type: 'directory' };
type Frontmatter = {
name: string;
description: string;
triggers: TriggerConfig[];
};
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: '', triggers: [] }, 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() ?? '';
const triggers: TriggerConfig[] = [];
const triggerMatch = yaml.match(/^trigger:\s*\n((?:[ \t]+.+\n?)*)/m);
if (triggerMatch) {
const items = triggerMatch[1]!.split(/(?=^\s+-\s*type:)/m);
for (const item of items) {
const type = item.match(/type:\s*(.+)/)?.[1]?.trim();
if (type === 'directory') {
triggers.push({ type: 'directory' });
} else if (type === 'file') {
const extBlock = item.match(/extensions:\s*\n((?:\s+-\s*.+\n?)*)/);
const extensions = extBlock ? [...extBlock[1]!.matchAll(/^\s+-\s*(.+)$/gm)].map((m) => m[1]!.trim()) : [];
if (extensions.length > 0) triggers.push({ type: 'file', extensions });
}
}
}
return { frontmatter: { name, description, triggers }, body, rawYaml: yaml };
}
export async function readTaskDirs(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 taskFile = join(dir, entry.name, 'TASK.md');
if (await Bun.file(taskFile).exists()) {
result.set(entry.name, taskFile);
}
}
} 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) { function isPrivileged(role: string) {
return role === 'Super Admin'; return role === 'Super Admin';
} }
@@ -80,29 +11,18 @@ export const tasksRouter = createRouter();
tasksRouter.get('/', async (ctx) => { tasksRouter.get('/', async (ctx) => {
const user = ctx.get('user'); const user = ctx.get('user');
const nativeTasks = await readTaskDirs(getNativeTasksDir()); const rows = await getTasksForUser(user.id);
const globalTasks = await readTaskDirs(getGlobalTasksDir());
const userTasks = await readTaskDirs(getUserTasksDir(user.email));
const merged = new Map(nativeTasks); const tasks = rows.map((row) => ({
for (const [name, path] of globalTasks) merged.set(name, path); id: row.id,
for (const [name, path] of userTasks) merged.set(name, path); dirName: row.dirName,
name: row.name,
const tasks = await Promise.all( description: row.description,
Array.from(merged.entries()).map(async ([dirName, filePath]) => { scope: row.scope,
const raw = await Bun.file(filePath).text(); triggers: (row.trigger as TriggerConfig[]) ?? [],
const { frontmatter } = parseFrontmatter(raw); mode: row.mode ?? 'agentic',
const scope = resolveScope(dirName, nativeTasks, globalTasks, userTasks); userId: row.userId,
return { }));
dirName,
name: frontmatter.name || dirName,
description: frontmatter.description,
scope,
triggers: frontmatter.triggers,
filePath,
};
}),
);
return ctx.json(tasks); return ctx.json(tasks);
}); });
@@ -111,127 +31,62 @@ tasksRouter.get('/:name', async (ctx) => {
const user = ctx.get('user'); const user = ctx.get('user');
const name = ctx.req.param('name'); const name = ctx.req.param('name');
const nativeTasks = await readTaskDirs(getNativeTasksDir()); const task = await getTaskByDirName(name, user.id);
const globalTasks = await readTaskDirs(getGlobalTasksDir()); if (!task) return ctx.text('Not found', 404);
const userTasks = await readTaskDirs(getUserTasksDir(user.email));
const resolved = resolveFile(name, nativeTasks, globalTasks, userTasks);
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({ return ctx.json({
name: frontmatter.name || name, id: task.id,
description: frontmatter.description, dirName: task.dirName,
scope: resolved.scope, name: task.name,
body, description: task.description,
rawFrontmatter: rawYaml, scope: task.scope,
filePath: resolved.filePath, mode: task.mode,
chatSessionId, language: task.language,
body: task.body,
implementation: task.implementation,
inputs: task.inputs,
args: task.args,
trigger: task.trigger,
version: task.version,
userId: task.userId,
}); });
}); });
tasksRouter.get('/:name/chat', async (ctx) => {
const user = ctx.get('user');
const name = ctx.req.param('name');
const nativeTasks = await readTaskDirs(getNativeTasksDir());
const globalTasks = await readTaskDirs(getGlobalTasksDir());
const userTasks = await readTaskDirs(getUserTasksDir(user.email));
const resolved = resolveFile(name, nativeTasks, globalTasks, userTasks);
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 });
});
tasksRouter.put('/:name/chat', async (ctx) => {
const user = ctx.get('user');
const name = ctx.req.param('name');
const nativeTasks = await readTaskDirs(getNativeTasksDir());
const globalTasks = await readTaskDirs(getGlobalTasksDir());
const userTasks = await readTaskDirs(getUserTasksDir(user.email));
const resolved = resolveFile(name, nativeTasks, globalTasks, userTasks);
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 });
});
tasksRouter.delete('/:name/chat', async (ctx) => {
const user = ctx.get('user');
const name = ctx.req.param('name');
const nativeTasks = await readTaskDirs(getNativeTasksDir());
const globalTasks = await readTaskDirs(getGlobalTasksDir());
const userTasks = await readTaskDirs(getUserTasksDir(user.email));
const resolved = resolveFile(name, nativeTasks, globalTasks, userTasks);
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 });
});
tasksRouter.post('/', async (ctx) => { tasksRouter.post('/', async (ctx) => {
const user = ctx.get('user'); const user = ctx.get('user');
const { name } = await ctx.req.json<{ name: string }>(); const body = await ctx.req.json<{ name: string; description?: string; mode?: string; language?: 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 (!body.name?.trim()) return ctx.text('Name is required', 400);
const dirName = body.name.trim().toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '');
if (!dirName) return ctx.text('Invalid name', 400); if (!dirName) return ctx.text('Invalid name', 400);
const targetDir = isPrivileged(user.role) ? getGlobalTasksDir() : getUserTasksDir(user.email); const scope = isPrivileged(user.role) ? 'global' : 'user';
const scope: Scope = isPrivileged(user.role) ? 'global' : 'user';
const dir = join(targetDir, dirName); const task = await createTask({
const filePath = join(dir, 'TASK.md'); scope,
userId: user.id,
dirName,
name: body.name.trim(),
description: body.description ?? null,
mode: body.mode ?? 'agentic',
language: body.language ?? null,
});
if (await Bun.file(filePath).exists()) { return ctx.json(task);
return ctx.text('Task 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 });
}); });
tasksRouter.delete('/:name', async (ctx) => { tasksRouter.delete('/:name', async (ctx) => {
const user = ctx.get('user'); const user = ctx.get('user');
const name = ctx.req.param('name'); const name = ctx.req.param('name');
const nativeTasks = await readTaskDirs(getNativeTasksDir()); const task = await getTaskByDirName(name, user.id);
const globalTasks = await readTaskDirs(getGlobalTasksDir()); if (!task) return ctx.text('Not found', 404);
const userTasks = await readTaskDirs(getUserTasksDir(user.email));
const resolved = resolveFile(name, nativeTasks, globalTasks, userTasks); // Only owner or Super Admin can delete
if (!resolved) return ctx.text('Not found', 404); if (task.scope === 'native') return ctx.text('Cannot delete native tasks', 403);
if (task.userId !== user.id && !isPrivileged(user.role)) return ctx.text('Forbidden', 403);
if (resolved.scope !== 'user' && !isPrivileged(user.role)) return ctx.text('Forbidden', 403); await deleteTask(task.id);
await rm(dirname(resolved.filePath), { recursive: true });
return ctx.json({ ok: true }); return ctx.json({ ok: true });
}); });
@@ -8,6 +8,7 @@ import { usePiChat, MessageBubble, StreamingBubble, ModelSelector } from '../../
import { useSettings } from 'state/useSettings'; import { useSettings } from 'state/useSettings';
import { useUserVisibleModels } from 'state/useModels'; import { useUserVisibleModels } from 'state/useModels';
import type { TaskSummary } from '../../useTasks'; import type { TaskSummary } from '../../useTasks';
import { useTaskRunner } from './useTaskRunner';
const playDing = () => { const playDing = () => {
const ctx = new AudioContext(); const ctx = new AudioContext();
@@ -190,6 +191,97 @@ const PiMonoInner = ({ defaultInput, cwd, initialModel, taskInfo, sandboxed }: P
); );
}; };
// ── Script-mode runner ──
type ScriptRunnerProps = {
taskDirName: string;
inputs: Record<string, string>;
cwd?: string;
};
const ScriptRunner = ({ taskDirName, inputs, cwd }: ScriptRunnerProps) => {
const runner = useTaskRunner();
const bottomRef = useRef<HTMLDivElement | null>(null);
// Auto-scroll
useEffect(() => {
bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [runner.output]);
// Ding on completion
const prevPhaseRef = useRef(runner.phase);
useEffect(() => {
if (prevPhaseRef.current === 'running' && runner.phase === 'done') {
playDing();
}
prevPhaseRef.current = runner.phase;
}, [runner.phase]);
const handleRun = () => {
runner.run(taskDirName, inputs, cwd);
};
if (runner.phase === 'ready') {
return (
<div className="flex-1 flex items-center justify-center">
<button
onClick={handleRun}
disabled={!runner.isConnected}
className="flex items-center gap-2 px-6 py-2.5 rounded-lg bg-duck-teal text-white font-medium text-sm hover:bg-duck-teal/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
>
<Play className="h-4 w-4" />
Run
</button>
</div>
);
}
return (
<div className="flex-1 flex flex-col min-h-0">
<div className="flex-1 min-h-0 overflow-y-auto px-4 py-3">
<pre className="text-xs font-mono whitespace-pre-wrap break-words">
{runner.output.map((line, i) => (
<span
key={i}
className={
line.stream === 'stderr'
? 'text-red-400'
: line.stream === 'system'
? 'text-duck-teal/70'
: 'text-foreground'
}
>
{line.text}
</span>
))}
</pre>
<div ref={bottomRef} />
</div>
<div className="shrink-0 flex justify-center py-3 border-t border-duck-dark/10">
{runner.phase === 'running' ? (
<button
onClick={runner.stop}
className="flex items-center gap-2 px-4 py-1.5 rounded-lg bg-red-500/10 text-red-600 text-sm font-medium hover:bg-red-500/20 transition-colors cursor-pointer"
>
<Square className="h-3.5 w-3.5" />
Stop
</button>
) : runner.exitCode !== 0 ? (
<span className="flex items-center gap-2 text-sm text-red-500 font-medium">
<CircleX className="h-4 w-4" />
Task failed (exit {runner.exitCode})
</span>
) : (
<span className="flex items-center gap-2 text-sm text-green-500 font-medium">
<CircleCheck className="h-4 w-4" />
Task complete
</span>
)}
</div>
</div>
);
};
type TaskRunnerModalProps = { type TaskRunnerModalProps = {
open: boolean; open: boolean;
onOpenChange: (open: boolean) => void; onOpenChange: (open: boolean) => void;
@@ -207,12 +299,19 @@ export const TaskRunnerModal = ({ open, onOpenChange, task, entryName, entryFull
const { settings } = useSettings(); const { settings } = useSettings();
const taskSettings = settings.tasks; const taskSettings = settings.tasks;
const entryRef = entryFullPath ?? entryName; const entryRef = entryFullPath ?? entryName;
const isScript = task.mode === 'script';
// Agentic mode prompt
const defaultInput = promptOverride const defaultInput = promptOverride
?? (entryRef && entryType ?? (entryRef && entryType
? `Read the task instructions at ${task.filePath} and execute them on the ${entryType}: ${entryRef}` ? `Execute the task "${task.name}" (${task.dirName}) on the ${entryType}: ${entryRef}`
: `Read the task instructions at ${task.filePath} and execute them`); : `Execute the task "${task.name}" (${task.dirName})`);
const taskInfo: TaskInfo = { taskName: task.name, taskDirName: task.dirName, entryName: entryName ?? '', entryType: entryType ?? 'file' }; const taskInfo: TaskInfo = { taskName: task.name, taskDirName: task.dirName, entryName: entryName ?? '', entryType: entryType ?? 'file' };
// Script mode inputs — for now, map the entry path to file_path
const scriptInputs: Record<string, string> = {};
if (entryFullPath) scriptInputs.file_path = entryFullPath;
return ( return (
<Dialog open={open} onOpenChange={onOpenChange}> <Dialog open={open} onOpenChange={onOpenChange}>
<DialogPortal> <DialogPortal>
@@ -238,15 +337,24 @@ export const TaskRunnerModal = ({ open, onOpenChange, task, entryName, entryFull
)} )}
</div> </div>
{/* Task Runner */} {/* Task Runner — branch on mode */}
<PiMonoInner {isScript ? (
key="pi" <ScriptRunner
defaultInput={defaultInput} key="script"
cwd={cwd} taskDirName={task.dirName}
initialModel={taskSettings.defaultProvider === 'pi' ? taskSettings.defaultModel : null} inputs={scriptInputs}
taskInfo={taskInfo} cwd={cwd.path || undefined}
sandboxed={sandboxed} />
/> ) : (
<PiMonoInner
key="pi"
defaultInput={defaultInput}
cwd={cwd}
initialModel={taskSettings.defaultProvider === 'pi' ? taskSettings.defaultModel : null}
taskInfo={taskInfo}
sandboxed={sandboxed}
/>
)}
</DialogPrimitive.Content> </DialogPrimitive.Content>
</DialogPortal> </DialogPortal>
</Dialog> </Dialog>
@@ -0,0 +1,82 @@
import { useState, useEffect, useRef, useCallback } from 'react';
type Phase = 'ready' | 'running' | 'done';
type ServerMessage =
| { type: 'started'; taskName: string }
| { type: 'stdout'; data: string }
| { type: 'stderr'; data: string }
| { type: 'exit'; code: number }
| { type: 'error'; message: string };
export function useTaskRunner() {
const [phase, setPhase] = useState<Phase>('ready');
const [output, setOutput] = useState<Array<{ stream: 'stdout' | 'stderr' | 'system'; text: string }>>([]);
const [exitCode, setExitCode] = useState<number | null>(null);
const [isConnected, setIsConnected] = useState(false);
const wsRef = useRef<WebSocket | null>(null);
useEffect(() => {
const token = localStorage.getItem('BEARER_TOKEN');
if (!token) return;
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const url = `${protocol}//${window.location.host}/api/tasks/run/ws?token=${token}`;
const ws = new WebSocket(url);
wsRef.current = ws;
ws.addEventListener('open', () => setIsConnected(true));
ws.addEventListener('close', () => setIsConnected(false));
ws.addEventListener('message', (ev) => {
try {
const msg = JSON.parse(ev.data) as ServerMessage;
switch (msg.type) {
case 'started':
setOutput((prev) => [...prev, { stream: 'system', text: `Running: ${msg.taskName}\n` }]);
break;
case 'stdout':
setOutput((prev) => [...prev, { stream: 'stdout', text: msg.data }]);
break;
case 'stderr':
setOutput((prev) => [...prev, { stream: 'stderr', text: msg.data }]);
break;
case 'exit':
setExitCode(msg.code);
setPhase('done');
break;
case 'error':
setOutput((prev) => [...prev, { stream: 'stderr', text: `Error: ${msg.message}\n` }]);
setPhase('done');
setExitCode(-1);
break;
}
} catch {
// ignore
}
});
return () => {
ws.close();
wsRef.current = null;
};
}, []);
const run = useCallback((taskDirName: string, inputs: Record<string, string>, cwd?: string) => {
if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) return;
setPhase('running');
setOutput([]);
setExitCode(null);
wsRef.current.send(JSON.stringify({ type: 'run', taskDirName, inputs, cwd }));
}, []);
const stop = useCallback(() => {
if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) return;
wsRef.current.send(JSON.stringify({ type: 'stop' }));
}, []);
return { phase, output, exitCode, isConnected, run, stop };
}
@@ -4,12 +4,14 @@ import { useClient } from 'hooks/useClient';
type TriggerConfig = { type: 'file'; extensions: string[] } | { type: 'directory' }; type TriggerConfig = { type: 'file'; extensions: string[] } | { type: 'directory' };
export type TaskSummary = { export type TaskSummary = {
id: number;
dirName: string; dirName: string;
name: string; name: string;
description: string; description: string;
scope: 'user' | 'global'; scope: string;
triggers: TriggerConfig[]; triggers: TriggerConfig[];
filePath: string; mode: 'script' | 'agentic';
userId: number | null;
}; };
export const useTasks = () => { export const useTasks = () => {