-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoffload.ts
More file actions
executable file
·210 lines (181 loc) · 8.24 KB
/
offload.ts
File metadata and controls
executable file
·210 lines (181 loc) · 8.24 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
#!/usr/bin/env bun
import { $ } from "bun";
import { join } from "path";
import { homedir } from "os";
import { appendFile, mkdir } from "fs/promises";
const CLAUDE_PATH = process.env.OFFLOAD_CLAUDE_PATH || "claude";
const CALENDAR_NAME = process.env.OFFLOAD_CALENDAR || "Calendar";
const NOTES_FOLDER = process.env.OFFLOAD_NOTES_FOLDER || "Offload";
const SHOPPING_LIST = process.env.OFFLOAD_SHOPPING_LIST || "Shopping";
const LOG_DIR = join(homedir(), ".offload");
const LOG_FILE = join(LOG_DIR, "offload.log");
function esc(s: string): string {
return s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n");
}
// --- AppleScript actions ---
async function createEvent({ title, year, month, day, hour, minute = 0, duration_hours = 1 }: { title: string; year: number; month: number; day: number; hour: number; minute?: number; duration_hours?: number }) {
const script = `
set startDate to current date
set year of startDate to ${year}
set month of startDate to ${month}
set day of startDate to ${day}
set hours of startDate to ${hour}
set minutes of startDate to ${minute}
set seconds of startDate to 0
set endDate to startDate + (${duration_hours} * hours)
tell application "Calendar"
tell calendar "${CALENDAR_NAME}"
make new event with properties {summary:"${esc(title)}", start date:startDate, end date:endDate}
end tell
end tell
`;
await $`osascript -e ${script}`.quiet();
const timeStr = `${month}/${day}/${year} ${hour}:${minute.toString().padStart(2, "0")}`;
const openCmd = `osascript -e 'tell application "Calendar"' -e 'activate' -e 'switch view to day view' -e 'set targetDate to current date' -e 'set year of targetDate to ${year}' -e 'set month of targetDate to ${month}' -e 'set day of targetDate to ${day}' -e 'view calendar at targetDate' -e 'end tell'`;
return { title: "Event created", message: `${title} at ${timeStr}`, openCmd };
}
async function addTodo({ task, notes }: { task: string; notes?: string }) {
const notesLine = notes
? `\nset body of newReminder to "${esc(notes)}"`
: "";
const script = `tell application "Reminders"
set newReminder to make new reminder with properties {name:"${esc(task)}"}${notesLine}
end tell`;
await $`osascript -e ${script}`.quiet();
return { title: "Todo added", message: task, openCmd: "open -b com.apple.reminders" };
}
async function setReminder({ task, year, month, day, hour = 9, minute = 0 }: { task: string; year: number; month: number; day: number; hour?: number; minute?: number }) {
const script = `
set remindDate to current date
set year of remindDate to ${year}
set month of remindDate to ${month}
set day of remindDate to ${day}
set hours of remindDate to ${hour}
set minutes of remindDate to ${minute}
set seconds of remindDate to 0
tell application "Reminders"
make new reminder with properties {name:"${esc(task)}", remind me date:remindDate}
end tell
`;
await $`osascript -e ${script}`.quiet();
const timeStr = `${month}/${day}/${year} ${hour}:${minute.toString().padStart(2, "0")}`;
return { title: "Reminder set", message: `${task} at ${timeStr}`, openCmd: "open -b com.apple.reminders" };
}
async function saveNote({ title, body }: { title: string; body: string }) {
const script = `tell application "Notes"
set offloadFolder to folder "${NOTES_FOLDER}"
make new note in offloadFolder with properties {name:"${esc(title)}", body:"${esc(body)}"}
end tell`;
await $`osascript -e ${script}`.quiet();
return { title: "Note saved", message: title, openCmd: "open -b com.apple.Notes" };
}
async function addShoppingItem({ items }: { items: string[] }) {
const lines = items
.map((item) => `make new reminder in shoppingList with properties {name:"${esc(item)}"}`)
.join("\n ");
const script = `tell application "Reminders"
set shoppingList to list "${SHOPPING_LIST}"
${lines}
end tell`;
await $`osascript -e ${script}`.quiet();
const msg = items.join(", ");
return { title: "Shopping added", message: msg, openCmd: "open -b com.apple.reminders" };
}
const dispatch: Record<string, (input: any) => Promise<any>> = {
create_event: createEvent,
add_todo: addTodo,
set_reminder: setReminder,
save_note: saveNote,
add_shopping_item: addShoppingItem,
};
// --- Main ---
async function checkDep(cmd: string, hint: string) {
const result = await $`which ${cmd}`.nothrow().quiet();
if (result.exitCode !== 0) {
console.error(`Error: "${cmd}" not found.\n${hint}`);
process.exit(1);
}
}
await checkDep(CLAUDE_PATH, "Install Claude Code: https://docs.anthropic.com/en/docs/claude-code");
await checkDep("terminal-notifier", "Install with: brew install terminal-notifier");
const today = new Date();
const dateReadable = today.toLocaleDateString("en-US", {
weekday: "long", year: "numeric", month: "long", day: "numeric",
});
const dateISO = `${today.getFullYear()}-${(today.getMonth() + 1).toString().padStart(2, "0")}-${today.getDate().toString().padStart(2, "0")}`;
const SYSTEM_PROMPT = `You are an offload assistant. Today is ${dateReadable} (${dateISO}).
The user types a quick thought. Respond with ONLY a JSON object, no markdown, no explanation.
Actions:
- create_event: {action:"create_event", title, year, month, day, hour, minute?, duration_hours?}
- add_todo: {action:"add_todo", task, notes?}
- set_reminder: {action:"set_reminder", task, year, month, day, hour?, minute?}
- save_note: {action:"save_note", title, body}
- add_shopping_item: {action:"add_shopping_item", items:[...]}
Rules:
- Resolve relative dates: "today" = ${dateISO}, "tomorrow" = next day, "Tuesday" = next upcoming Tuesday
- Use 24h time. Default hour=9, minute=0 if no time given.
- Default duration_hours=1.
- For shopping with multiple items, use add_shopping_item with items array.
- If unclear, default to save_note.`;
async function offload(input: string) {
const prompt = SYSTEM_PROMPT + "\n\nUser: " + input;
const env = { ...process.env, CLAUDECODE: "" };
const proc = Bun.spawn([CLAUDE_PATH, "--model", "haiku", "--output-format", "json", "-p", prompt], {
stdin: null, stdout: "pipe", stderr: "pipe", env,
});
const stdout = await new Response(proc.stdout).text();
const exitCode = await proc.exited;
if (exitCode !== 0) {
const stderr = await new Response(proc.stderr).text();
throw new Error(`claude exited ${exitCode}: ${stderr.slice(0, 200)}`);
}
const response = JSON.parse(stdout);
const text = response.result.replace(/^```(?:json)?\n?/, "").replace(/\n?```$/, "").trim();
const parsed = JSON.parse(text);
const { action, ...args } = parsed;
const handler = dispatch[action];
if (!handler) throw new Error(`Unknown action: ${action}`);
return { ...(await handler(args)), tool: action, args };
}
const input = process.argv.slice(2).join(" ");
if (!input) {
console.log("Usage: offload <anything>");
process.exit(1);
}
try {
const start = performance.now();
const action = await offload(input);
const duration = ((performance.now() - start) / 1000).toFixed(1);
const title = action.title;
const message = action.message;
const safeTitle = title.replace(/"/g, '\\"');
const safeMessage = `${message} (${duration}s)`.replace(/"/g, '\\"');
if (action.openCmd) {
await $`terminal-notifier -title ${safeTitle} -message ${safeMessage} -execute ${action.openCmd} -ignoreDnD`.nothrow().quiet();
} else {
await $`terminal-notifier -title ${safeTitle} -message ${safeMessage} -ignoreDnD`.nothrow().quiet();
}
await mkdir(LOG_DIR, { recursive: true });
const logEntry = {
timestamp: new Date().toISOString(),
duration: `${duration}s`,
input,
tool: action.tool,
args: action.args,
result: `${title}: ${message}`,
};
await appendFile(LOG_FILE, JSON.stringify(logEntry) + "\n");
console.log(`${title}: ${message} (${duration}s)`);
} catch (error) {
const errMsg = String(error instanceof Error ? error.message : error);
console.error("Failed:", errMsg);
await mkdir(LOG_DIR, { recursive: true });
const logEntry = {
timestamp: new Date().toISOString(),
input,
error: errMsg.slice(0, 500),
};
await appendFile(LOG_FILE, JSON.stringify(logEntry) + "\n");
await $`terminal-notifier -title "Offload Error" -message ${errMsg.slice(0, 100)} -ignoreDnD`.nothrow().quiet();
process.exit(1);
}