-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit.lua
More file actions
226 lines (198 loc) · 6.64 KB
/
Copy pathinit.lua
File metadata and controls
226 lines (198 loc) · 6.64 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
225
226
-- fettle — prototype
-- The loop: hotkey -> Cmd+A, Cmd+C -> correct(text) -> paste back -> restore clipboard.
--
-- Correction engine: your own Anthropic API key + a model you pick from the
-- menu-bar dropdown. No bundled model, so the whole thing stays tiny.
local HOTKEY_MODS = { "alt" } -- Option
local HOTKEY_KEY = "space" -- Option+Space
local API_URL = "https://api.anthropic.com/v1/messages"
local API_VERSION = "2023-06-01"
local MAX_TOKENS = 2048
-- Key lives in Hammerspoon's config dir, OUTSIDE this repo, so a secret can
-- never be committed and the path works for anyone who installs the tool.
local KEY_FILE = hs.configdir .. "/fettle-key.txt"
-- Models you can pick between from the menu bar. Add/remove freely.
local MODELS = {
{ label = "Haiku 4.5 — fast & cheap", id = "claude-haiku-4-5-20251001" },
{ label = "Sonnet 5 — balanced", id = "claude-sonnet-5" },
{ label = "Opus 5 — best, slower", id = "claude-opus-5" },
}
local DEFAULT_MODEL = MODELS[1].id
local SETTING_MODEL = "fettle.model" -- persisted across reloads/restarts
-- British English, and a tight instruction to *only* return the corrected text.
local SYSTEM_PROMPT = table.concat({
"You fix text. Correct spelling, typos, grammar, and verb tense.",
"Preserve the original meaning, tone, punctuation style, and line breaks.",
"Use British English spelling (colour, organise, favour).",
"Do not rephrase or add anything; make the smallest changes needed to make it correct.",
"Return ONLY the corrected text — no quotes, no commentary, no explanation.",
"If the text is already correct, return it unchanged.",
}, " ")
-- Poll settings for waiting on the async clipboard copy to land.
local POLL_INTERVAL = 0.02 -- seconds between checks
local POLL_MAX_TRIES = 25 -- ~0.5s total timeout
local RESTORE_DELAY = 0.35 -- seconds to wait before restoring the old clipboard
local function trim(s)
return (s:gsub("^%s+", ""):gsub("%s+$", ""))
end
local function currentModel()
return hs.settings.get(SETTING_MODEL) or DEFAULT_MODEL
end
local function modelLabel(id)
for _, m in ipairs(MODELS) do
if m.id == id then
return m.label
end
end
return id
end
local function getApiKey()
local envKey = os.getenv("ANTHROPIC_API_KEY")
if envKey and envKey ~= "" then
return trim(envKey)
end
local f = io.open(KEY_FILE, "r")
if not f then
return nil
end
local contents = f:read("*a")
f:close()
local key = trim(contents or "")
return key ~= "" and key or nil
end
-- === the correction engine ==================================================
-- Async so the network round-trip never blocks the UI. Calls done(fixedText).
-- On any error we fall back to the original text (no destructive change).
local function correctAsync(text, done)
local key = getApiKey()
if not key then
hs.alert.show("fettle: no API key (add " .. KEY_FILE .. ")")
done(text)
return
end
local body = hs.json.encode({
model = currentModel(),
max_tokens = MAX_TOKENS,
system = SYSTEM_PROMPT,
messages = { { role = "user", content = text } },
})
local headers = {
["x-api-key"] = key,
["anthropic-version"] = API_VERSION,
["content-type"] = "application/json",
}
hs.http.asyncPost(API_URL, body, headers, function(status, respBody, _)
if status ~= 200 or not respBody then
local detail = respBody and trim(respBody):sub(1, 120) or "no response"
hs.alert.show("fettle: API error " .. tostring(status) .. " — " .. detail)
done(text)
return
end
local ok, parsed = pcall(hs.json.decode, respBody)
if not ok or type(parsed) ~= "table" or type(parsed.content) ~= "table" or not parsed.content[1] then
hs.alert.show("fettle: unexpected response")
done(text)
return
end
local fixed = trim(parsed.content[1].text or "")
if fixed == "" then
done(text)
else
done(fixed)
end
end)
end
-- =============================================================================
-- Wait for the pasteboard changeCount to move (i.e. our Cmd+C landed), with a
-- timeout so an empty/unsupported field can't hang us forever.
local function waitForCopy(startCount, onReady, triesLeft)
triesLeft = triesLeft or POLL_MAX_TRIES
if hs.pasteboard.changeCount() ~= startCount then
onReady(true)
elseif triesLeft <= 0 then
onReady(false)
else
hs.timer.doAfter(POLL_INTERVAL, function()
waitForCopy(startCount, onReady, triesLeft - 1)
end)
end
end
local function fixSelection()
local original = hs.pasteboard.getContents()
local startCount = hs.pasteboard.changeCount()
-- Grab whatever's in the focused field.
hs.eventtap.keyStroke({ "cmd" }, "a", 0)
hs.eventtap.keyStroke({ "cmd" }, "c", 0)
waitForCopy(startCount, function(copied)
if not copied then
hs.alert.show("fettle: nothing to grab")
return
end
local text = hs.pasteboard.getContents()
if not text or text == "" then
hs.alert.show("fettle: empty selection")
return
end
-- Immediate feedback so the network wait feels intentional, not laggy.
local fixingId = hs.alert.show("✍️ fettling…", hs.alert.defaultStyle, hs.screen.mainScreen(), 10)
correctAsync(text, function(fixed)
hs.alert.closeSpecific(fixingId)
hs.pasteboard.setContents(fixed)
hs.eventtap.keyStroke({ "cmd" }, "v", 0)
-- Give the paste a moment to consume the clipboard, then restore
-- whatever was there before so we don't clobber it.
hs.timer.doAfter(RESTORE_DELAY, function()
if original then
hs.pasteboard.setContents(original)
end
end)
end)
end)
end
-- === menu bar ===============================================================
local menubar = hs.menubar.new()
local function ensureKeyFileExists()
local f = io.open(KEY_FILE, "r")
if f then
f:close()
else
local w = io.open(KEY_FILE, "a")
if w then
w:close()
end
end
end
local function buildMenu()
local items = {
{ title = "fettle", disabled = true },
{ title = "-" },
{ title = "Model", disabled = true },
}
for _, m in ipairs(MODELS) do
table.insert(items, {
title = " " .. m.label,
checked = (m.id == currentModel()),
fn = function()
hs.settings.set(SETTING_MODEL, m.id)
hs.alert.show("fettle: model → " .. m.label)
end,
})
end
table.insert(items, { title = "-" })
table.insert(items, {
title = "Edit API key…",
fn = function()
ensureKeyFileExists()
hs.execute("open -e '" .. KEY_FILE .. "'")
end,
})
table.insert(items, { title = "Reload config", fn = function() hs.reload() end })
return items
end
if menubar then
menubar:setTitle("✍️")
menubar:setMenu(buildMenu)
end
-- =============================================================================
hs.hotkey.bind(HOTKEY_MODS, HOTKEY_KEY, fixSelection)
hs.alert.show("fettle loaded — Option+Space (" .. modelLabel(currentModel()) .. ")")