forked from doctly/switchboard
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathschedule-ipc.js
More file actions
224 lines (183 loc) · 8.97 KB
/
Copy pathschedule-ipc.js
File metadata and controls
224 lines (183 loc) · 8.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
// schedule-ipc.js — IPC handlers and helpers for scheduled task creation
const { ipcMain } = require('electron');
const path = require('path');
const fs = require('fs');
const os = require('os');
const crypto = require('crypto');
const { encodeProjectPath } = require('./encode-project-path');
const { resolveRunNowTarget } = require('./run-schedule-now-target');
const CLAUDE_DIR = path.join(os.homedir(), '.claude');
const PROJECTS_DIR = path.join(CLAUDE_DIR, 'projects');
const SCHEDULE_COMMANDS_DIR = path.join(CLAUDE_DIR, 'commands');
const SCHEDULE_CREATOR_TEMPLATE = `---
name: create-switchboard-schedule
description: Create a new Switchboard scheduled task for this project
---
You are helping the user create a scheduled task in Switchboard. This task will run automatically on a cron schedule using Claude Code CLI in headless mode (-p flag).
## Instructions for the user
Welcome! I'll help you set up a scheduled task for this project. Tell me:
- **What** the task should do
- **When** it should run (e.g. "every weekday at 9am", "hourly", "every Sunday night")
I'll generate the schedule file and save it. You can always edit it later from the brain tab.
## How to create the task
Ask the user what the task should do and when it should run. Keep it conversational — one or two questions at a time, not all at once.
Once you have enough information, generate a cron expression from their description and confirm it in plain english (e.g. "That's every weekday at 9:00 AM").
## File format
Save to \`<project-root>/.claude/commands/schedule-<slug>.md\`:
\`\`\`markdown
---
name: <Human readable name>
cron: <5-field cron expression>
enabled: true
slug: <short-kebab-case-id>
cli:
permission-mode: auto
allowed-tools: <select based on task needs>
# only include these if the user specified them:
# model: <model>
# max-budget-usd: <number>
# append-system-prompt: <extra context>
# add-dirs: <comma-separated paths>
---
<The full prompt that will be sent to Claude when this task runs>
\`\`\`
## Selecting permissions
Scheduled tasks run headless, so choose the minimum tools needed for the task. Available tools:
| Tool | Use when the task needs to... |
|------|-------------------------------|
| Bash | Run shell commands, scripts, tests, git operations |
| Read | Read files from the project |
| Write | Create new files |
| Edit | Modify existing files |
| Glob | Find files by name pattern |
| Grep | Search file contents |
| WebFetch | Fetch URLs, APIs, web pages |
| WebSearch | Search the web |
Examples:
- **Web scraping task** → \`Bash,Read,Write,Glob,WebFetch\`
- **Test runner** → \`Bash,Read,Glob,Grep\`
- **Code refactor** → \`Bash,Read,Write,Edit,Glob,Grep\`
- **Report generator** → \`Bash,Read,Write,Glob,Grep,WebFetch\`
Default permission-mode is \`auto\` (Claude classifies each action, allowing routine work and stopping for risky ones). Always include at least \`Read\` and \`Glob\`.
## Rules
- The slug must be kebab-case, short, and descriptive
- The prompt in the body must be fully self-contained — it runs without any conversation history
- If the \`.claude/commands/\` directory doesn't exist, create it
- After saving, tell the user: "Your scheduled task is saved! It will appear in Switchboard's brain tab with a schedule icon. You can enable/disable it or edit the schedule from there."
- If the user wants to see existing schedules, list any \`schedule-*.md\` files in \`.claude/commands/\`
`;
const SCHEDULE_WELCOME_MESSAGE = `## Switchboard Scheduled Task Creator
Welcome! This session will help you create a **scheduled task** that runs automatically on a cron schedule using Claude Code.
### How it works
- Describe **what** you want the task to do and **when** it should run
- I'll generate a schedule file with the right cron expression and prompt
- The schedule file gets saved to this project's \`.claude/commands/\` directory as a command — so it can also be run manually from any Claude session using \`/schedule-<name>\`
- Once saved, it appears in the **brain tab** with a clock icon where you can edit it directly
- To edit, you can also ask use this schedule claude session to ask to edit existing commands.
- Switchboard runs matching schedules automatically in the background — each run creates a session grouped under the task's slug
### What you can configure
- **The prompt** — what Claude should do each time the task runs
- **The schedule** — any cron pattern (e.g. "every weekday at 9am", "hourly", "first Monday of the month")
- **CLI settings** — model, permission mode, budget cap, allowed tools, additional directories
### To get started
Just describe the task you have in mind, or try one of these:
- **"What are my existing schedules?"** — list just the scheduled tasks
- **"Edit schedule-hn-digest to run every 5 minutes instead of hourly"** — modify an existing schedule
- **"Create a task that runs the test suite every morning at 8am"** — create a new one
- **"Disable schedule-repo-health"** — toggle a schedule off`;
function ensureScheduleCreatorCommand() {
try {
const commandPath = path.join(SCHEDULE_COMMANDS_DIR, 'create-switchboard-schedule.md');
if (!fs.existsSync(commandPath)) {
fs.mkdirSync(SCHEDULE_COMMANDS_DIR, { recursive: true });
fs.writeFileSync(commandPath, SCHEDULE_CREATOR_TEMPLATE);
}
} catch (err) {
console.error('[schedule] Failed to create schedule command:', err);
}
}
function init(log, runCommand, isPathAllowed) {
const { parseFrontmatter, createScheduleSession, buildScheduleCommand } = require('./schedule-runner');
ipcMain.handle('get-schedule-creator-command', () => {
try {
const commandPath = path.join(SCHEDULE_COMMANDS_DIR, 'create-switchboard-schedule.md');
ensureScheduleCreatorCommand();
return fs.readFileSync(commandPath, 'utf8');
} catch (err) {
log.error('[schedule] Failed to read schedule command:', err);
return null;
}
});
ipcMain.handle('create-schedule-session', (_event, projectPath) => {
try {
ensureScheduleCreatorCommand();
const commandPath = path.join(SCHEDULE_COMMANDS_DIR, 'create-switchboard-schedule.md');
const systemPrompt = fs.readFileSync(commandPath, 'utf8');
const sessionId = crypto.randomUUID();
const msgId = crypto.randomUUID();
const timestamp = new Date().toISOString();
const folder = encodeProjectPath(projectPath);
const claudeProjectDir = path.join(PROJECTS_DIR, folder);
fs.mkdirSync(claudeProjectDir, { recursive: true });
const jsonlPath = path.join(claudeProjectDir, `${sessionId}.jsonl`);
const snapshot = JSON.stringify({
type: 'file-history-snapshot',
messageId: msgId,
snapshot: { messageId: msgId, trackedFileBackups: {}, timestamp },
isSnapshotUpdate: false,
});
const assistantMsg = JSON.stringify({
parentUuid: null,
isSidechain: false,
userType: 'external',
cwd: projectPath,
sessionId,
version: '1.0.0',
gitBranch: 'main',
slug: 'create-schedule',
type: 'assistant',
message: { role: 'assistant', content: [{ type: 'text', text: SCHEDULE_WELCOME_MESSAGE }] },
uuid: msgId,
timestamp,
});
fs.writeFileSync(jsonlPath, snapshot + '\n' + assistantMsg + '\n');
log.info(`[schedule] Pre-created schedule session ${sessionId} for ${projectPath}`);
return { sessionId, systemPrompt };
} catch (err) {
log.error('[schedule] Failed to create schedule session:', err);
return null;
}
});
ipcMain.handle('run-schedule-now', (_event, filePath) => {
try {
const target = resolveRunNowTarget(filePath, isPathAllowed);
if (!target.ok) {
log.warn(`[schedule] Refused run-schedule-now for ${JSON.stringify(filePath)}: ${target.error}`);
return { ok: false, error: target.error };
}
const { realPath, projectPath } = target;
const content = fs.readFileSync(realPath, 'utf8');
const { meta, body } = parseFrontmatter(content);
if (!body) return { ok: false, error: 'No prompt in schedule file' };
const folder = encodeProjectPath(projectPath);
const schedule = {
file: path.basename(realPath),
filePath: realPath, projectPath, folder,
name: meta.name || path.basename(realPath),
cron: meta.cron || '* * * * *',
slug: meta.slug || path.basename(realPath, '.md').replace(/^schedule-/, ''),
cli: meta.cli || {},
prompt: body,
};
const { sessionId } = createScheduleSession(schedule);
const { claudeArgs } = buildScheduleCommand(sessionId, schedule);
runCommand(claudeArgs, projectPath, `Manual run ${schedule.name}`, () => {});
log.info(`[schedule] Manual run triggered: ${schedule.name} (session ${sessionId})`);
return { ok: true, sessionId };
} catch (err) {
log.error('[schedule] Failed to run schedule:', err);
return { ok: false, error: err.message };
}
});
}
module.exports = { ensureScheduleCreatorCommand, init };