import { Plugin } from "@opencode/plugin"; import { TaskDatabase, getDefaultDbPath } from "./lib/db.js"; import { readAllTasks, getTasksDir, setTaskEnabled } from "./lib/tasks.js"; import { getNextRunTime } from "./lib/cron.js"; import { isInstalled } from "./lib/installer.js"; import { scheduleOneoffTask, formatScheduledTaskMessage } from "./lib/schedule.js"; import { executeStartLoopTool, executeListLoopsTool, executeStopLoopTool } from "./lib/loop-tools.js"; import { loopCommand } from "./lib/loop-commands.js"; import { taskInstructions } from "./lib/instructions.js"; function withDb(run: (db: TaskDatabase) => T): T { const db = new TaskDatabase(getDefaultDbPath()); try { return run(db); } finally { db.close(); } } function warning(): string { return isInstalled() ? "" : "\n\nDaemon not installed. Run: bunx opencode-tasks --install (or run ticks manually)."; } const string = (description: string) => ({ type: "string" as const, description }); export default Plugin.define({ id: "opencode-tasks", async setup(ctx) { await ctx.tool.transform((editor) => { const add = (name: string, description: string, properties: Record, required: string[], execute: (input: any, context: { sessionID: string }) => string | Promise) => { editor.add({ name, description, input: { type: "object", properties, required, additionalProperties: false }, async execute(input, context) { try { return { content: await execute(input, context) }; } catch (error) { return { content: `Error: ${error instanceof Error ? error.message : error}` }; } }, }); }; add("schedule_task", "Schedule a one-off background task through the daemon.", { prompt: string("Prompt"), description: string("Description"), cwd: string("Absolute working directory"), scheduled_at: string("ISO 8601 timestamp"), session_name: string("Reuse this named session"), model: string("provider/model#variant"), agent: string("Agent name"), permission: string("JSON V2 ordered ruleset [{action,resource,effect}]. Legacy V1 objects also accepted. Unattended asks are rejected."), }, ["prompt", "description", "cwd", "scheduled_at"], (args, context) => withDb((db) => formatScheduledTaskMessage(scheduleOneoffTask(db, { ...args, scheduledAt: args.scheduled_at, sessionName: args.session_name, createdBySession: context.sessionID, rejectPastDate: true })) + warning())); add("list_tasks", "List recurring and one-off tasks.", { status: { type: "string", enum: ["all", "pending", "completed", "failed"] }, type: { type: "string", enum: ["all", "recurring", "oneoff"] }, }, [], (args) => withDb((db) => { const lines: string[] = []; if (!args.type || args.type === "all" || args.type === "recurring") { const { tasks, errors } = readAllTasks(); for (const task of tasks) { let nextRun = "disabled"; if (task.enabled) { try { nextRun = getNextRunTime(task.schedule); } catch { nextRun = "invalid cron expression"; } } lines.push(`${task.name}: ${nextRun}; cwd: ${task.cwd}; last: ${db.getLastTaskRun(task.name)?.status ?? "never"}`); } lines.push(...errors.map(({ file, error }) => `${file}: ${error}`)); } if (!args.type || args.type === "all" || args.type === "oneoff") { for (const task of db.listOneoffTasks({ status: args.status ?? "all" })) { lines.push(`${task.id}: ${task.description} [${task.status}] at ${task.scheduledAt}; cwd: ${task.cwd}${task.sessionId ? `; session: ${task.sessionId}` : ""}${task.error ? `; error: ${task.error}` : ""}`); } } return (lines.join("\n") || "No tasks found.") + warning(); })); add("cancel_task", "Cancel a pending one-off task or disable a recurring task.", { id: string("Task ID or name") }, ["id"], (args) => withDb((db) => { const oneoff = db.getOneoffTask(args.id); if (oneoff) return db.cancelOneoffTask(args.id) ? `Cancelled ${args.id}` : `Cannot cancel task with status ${oneoff.status}`; const task = readAllTasks().tasks.find((task) => task.name === args.id); if (!task) return `No task found: ${args.id}`; setTaskEnabled(task.filePath, false); return `Disabled ${task.name}`; })); const loopContext = (context: { sessionID: string }) => ({ ...context, directory: ctx.location.directory }); add("start_loop", "Start a daemon-backed recurring prompt in this session. Defaults to 5m and expires after 3 days.", { prompt: string("Prompt"), interval: string("Interval: 5m, 2h, or 1d"), }, ["prompt"], (args, context) => withDb((db) => executeStartLoopTool(args, loopContext(context), db) + warning())); add("list_loops", "List active loops in this session.", {}, [], (_args, context) => withDb((db) => executeListLoopsTool(loopContext(context), db))); add("stop_loop", "Stop a loop in this session.", { id: { ...string("Full ID or unambiguous prefix"), minLength: 8 } }, ["id"], (args, context) => withDb((db) => executeStopLoopTool(args, loopContext(context), db))); add("task_history", "Show recent task runs, outcomes, sessions, and errors.", { task_name: string("Recurring task name or one-off ID"), limit: { type: "integer", minimum: 1 }, }, ["task_name"], (args) => withDb((db) => { const oneoff = db.getOneoffTask(args.task_name); if (oneoff) { const lines = [ `## One-off Task: ${oneoff.description}\n`, `- ID: ${oneoff.id}`, `- Status: ${oneoff.status}`, `- Scheduled: ${oneoff.scheduledAt}`, `- Created: ${oneoff.createdAt}`, `- CWD: ${oneoff.cwd}`, ]; if (oneoff.executedAt) lines.push(`- Executed: ${oneoff.executedAt}`); if (oneoff.sessionId) lines.push(`- Session: ${oneoff.sessionId}`); if (oneoff.error) lines.push(`- Error: ${oneoff.error}`); return lines.join("\n"); } const runs = db.getTaskRunHistory(args.task_name, args.limit ?? 10); if (!runs.length) return `No history found for task "${args.task_name}"`; const lines = [`## History for "${args.task_name}"\n`]; for (const run of runs) { lines.push(`- **${run.status}** at ${run.startedAt}`); if (run.completedAt) lines.push(` Duration: ${Math.round((new Date(run.completedAt).getTime() - new Date(run.startedAt).getTime()) / 1000)}s`); if (run.sessionId) lines.push(` Session: ${run.sessionId}`); if (run.error) lines.push(` Error: ${run.error}`); } return lines.join("\n"); })); add("get_task_instructions", "Get the recurring task frontmatter format and permission instructions.", {}, [], () => taskInstructions(getTasksDir())); }); await ctx.command.transform((editor) => { for (const name of ["loop", "loop-stop", "loop-list"]) { editor.add({ name, description: { loop: "Start a session loop: [interval] [prompt]", "loop-stop": "Stop one or all session loops", "loop-list": "List session loops" }[name], async execute({ sessionID, prompt, delivery }) { let result: string; try { result = withDb((db) => loopCommand(name, prompt.text, sessionID, ctx.location.directory, db)); } catch (error) { result = `Error: ${error instanceof Error ? error.message : error}`; } // V2 displays a synthetic input's description; resume:false avoids an LLM acknowledgement. await ctx.session.synthetic({ sessionID, text: result, description: result, delivery, resume: false }); }, }); } }); }, });