sumo-agents 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +38 -0
- package/LICENSE +21 -0
- package/README.md +111 -2
- package/bin/sumo.mjs +33 -0
- package/guides/delegation.md +33 -0
- package/guides/feature.md +14 -0
- package/guides/fix.md +14 -0
- package/guides/memory.md +23 -0
- package/guides/projects.md +27 -0
- package/guides/review.md +16 -0
- package/guides/workflows.md +26 -0
- package/logo.txt +19 -0
- package/package.json +42 -4
- package/prompts/agent.md +7 -0
- package/prompts/dream.md +13 -0
- package/prompts/scribe.md +21 -0
- package/spinner.txt +90 -0
- package/src/advisor.mjs +59 -0
- package/src/apply.mjs +368 -0
- package/src/auth.mjs +80 -0
- package/src/card.mjs +72 -0
- package/src/catalog.mjs +167 -0
- package/src/chat.mjs +1162 -0
- package/src/cli.mjs +815 -0
- package/src/cost.mjs +128 -0
- package/src/db.mjs +384 -0
- package/src/dream.mjs +97 -0
- package/src/editor.mjs +198 -0
- package/src/export.mjs +132 -0
- package/src/guard.mjs +121 -0
- package/src/guides.mjs +86 -0
- package/src/herdr.mjs +117 -0
- package/src/hooks.mjs +270 -0
- package/src/images.mjs +89 -0
- package/src/jobs.mjs +1184 -0
- package/src/jobtools.mjs +82 -0
- package/src/local-server.mjs +169 -0
- package/src/lock.mjs +45 -0
- package/src/loop.mjs +838 -0
- package/src/mcp.mjs +604 -0
- package/src/memory.mjs +400 -0
- package/src/model.mjs +270 -0
- package/src/page.html +304 -0
- package/src/page.mjs +135 -0
- package/src/paths.mjs +33 -0
- package/src/prime.mjs +177 -0
- package/src/projects.mjs +232 -0
- package/src/recall.mjs +45 -0
- package/src/redact.mjs +173 -0
- package/src/render.mjs +45 -0
- package/src/route.mjs +287 -0
- package/src/sandbox.mjs +173 -0
- package/src/scan.mjs +204 -0
- package/src/scribe.mjs +349 -0
- package/src/sessions.mjs +371 -0
- package/src/setup.mjs +528 -0
- package/src/sqlite.mjs +66 -0
- package/src/text.mjs +97 -0
- package/src/tools.mjs +987 -0
- package/src/transcript.mjs +106 -0
- package/src/tty.mjs +529 -0
- package/src/ui.mjs +1363 -0
- package/src/verify.mjs +369 -0
- package/src/web.mjs +49 -0
- package/src/workflows.mjs +270 -0
- package/src/worktree.mjs +128 -0
package/src/hooks.mjs
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import { appendFileSync, mkdirSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { card } from './card.mjs';
|
|
4
|
+
import { getMeta, openDb, setMeta } from './db.mjs';
|
|
5
|
+
import { backup } from './export.mjs';
|
|
6
|
+
import { guardCommand, guardPath } from './guard.mjs';
|
|
7
|
+
import { autoGuides, firingGuides, matchGuide, renderGuide } from './guides.mjs';
|
|
8
|
+
import { paths } from './paths.mjs';
|
|
9
|
+
import { prime } from './prime.mjs';
|
|
10
|
+
import { detect, keepScratch, touch } from './projects.mjs';
|
|
11
|
+
import { closingQuestions, recallBeforeAsking } from './recall.mjs';
|
|
12
|
+
import { line } from './render.mjs';
|
|
13
|
+
import { shouldRun, spawnDetached } from './scribe.mjs';
|
|
14
|
+
import { clearInjections, contextBand, contextNudge, contextUse, currentProject, endSession, ensureSession, injectedSlugs, markInjected, pruneStates, recordTurn, sessionsAwaitingDream } from './sessions.mjs';
|
|
15
|
+
import { claim, renderWorkflow, withoutSumoCalls } from './workflows.mjs';
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The session policy, as events: a session starts, the user speaks, a tool is
|
|
19
|
+
* about to run, a turn ends, the session ends. `sumo chat` raises them in
|
|
20
|
+
* process; `sumo hook <event>` raises one from JSON on stdin, for anything else
|
|
21
|
+
* that drives a session. Every handler returns what should be put in front of
|
|
22
|
+
* the model — text, or a decision as JSON — and nothing else.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
const BACKUP_EVERY_MS = 7 * 24 * 3_600_000;
|
|
26
|
+
const SESSIONS_TO_DREAM = 3;
|
|
27
|
+
|
|
28
|
+
/** The one event shape. Field names are what the payload carries; a missing one is simply absent. */
|
|
29
|
+
export function fieldsOf(p) {
|
|
30
|
+
return {
|
|
31
|
+
sessionId: p.session_id,
|
|
32
|
+
cwd: p.cwd ?? null,
|
|
33
|
+
transcriptPath: p.transcript_path ?? null,
|
|
34
|
+
source: p.source ?? null,
|
|
35
|
+
prompt: p.prompt ?? '',
|
|
36
|
+
toolName: String(p.tool_name ?? '').toLowerCase(),
|
|
37
|
+
command: p.tool_input?.command ?? '',
|
|
38
|
+
question: p.tool_input?.question ?? '',
|
|
39
|
+
path: p.tool_input?.path ?? p.tool_input?.file_path ?? '',
|
|
40
|
+
agentId: p.agent_id ?? null,
|
|
41
|
+
project: p.project ?? null,
|
|
42
|
+
reply: p.last_assistant_message ?? '',
|
|
43
|
+
contextTokens: Number.isFinite(p.context_tokens) ? p.context_tokens : null,
|
|
44
|
+
stopHookActive: p.stop_hook_active === true,
|
|
45
|
+
// A guide the user named by its command; the files the turn edited after a declared check last ran, and those checks.
|
|
46
|
+
guide: p.guide ?? null,
|
|
47
|
+
edited: Array.isArray(p.edited) ? p.edited.map(String) : [],
|
|
48
|
+
checks: Array.isArray(p.checks) ? p.checks.map(String) : [],
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const deny = (reason) => JSON.stringify({ deny: reason });
|
|
53
|
+
const isRead = (tool) => tool === 'read' || tool === 'view';
|
|
54
|
+
|
|
55
|
+
/** The guard, first and without memory: a destructive command or a secret file is refused on sight. */
|
|
56
|
+
export function earlyRefusal(e) {
|
|
57
|
+
if (e.toolName === 'bash' && e.command) return guardCommand(e.command, { cwd: e.cwd }) ?? '';
|
|
58
|
+
if (isRead(e.toolName) && e.path) return guardPath(e.path) ?? '';
|
|
59
|
+
return '';
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const alreadyKnown = (known) => `memory already holds\n${known.map(line).join('\n')}\nIf one of these answers your question, act on it instead of asking.`;
|
|
63
|
+
|
|
64
|
+
/** Global workflows always apply; a project's apply once that project has come up in the session. */
|
|
65
|
+
const scopesOf = (db, sessionId) => ['global', ...injectedSlugs(db, sessionId).map((slug) => `project:${slug}`)];
|
|
66
|
+
|
|
67
|
+
/** What a fresh start should be told to keep: the job in hand if there is one, otherwise the project the session is about. */
|
|
68
|
+
function focusOf(db, sessionId) {
|
|
69
|
+
const job = db.prepare(`SELECT title FROM jobs WHERE status IN ('running', 'needs_input') ORDER BY id DESC LIMIT 1`).get();
|
|
70
|
+
return job?.title ?? currentProject(db, sessionId) ?? 'the work in hand';
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* How big this session has got. Said once per band — remembered the same way a
|
|
75
|
+
* card that has been shown is remembered, so a fresh start (which clears those)
|
|
76
|
+
* lets it be said again, which is right: the context really did shrink.
|
|
77
|
+
*/
|
|
78
|
+
function sizeNudge(db, e, now) {
|
|
79
|
+
const tokens = e.contextTokens ?? contextUse(e.transcriptPath)?.tokens ?? null;
|
|
80
|
+
const band = tokens !== null && contextBand(tokens);
|
|
81
|
+
if (!band) return '';
|
|
82
|
+
const slug = `context:${band}`;
|
|
83
|
+
if (db.prepare('SELECT 1 FROM session_injections WHERE session_id = ? AND slug = ?').get(e.sessionId, slug)) return '';
|
|
84
|
+
markInjected(db, e.sessionId, slug, now);
|
|
85
|
+
return contextNudge(band, focusOf(db, e.sessionId));
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The guide for the kind of work the message asks for, once per session — unless a taught workflow matched the
|
|
90
|
+
* same message: the user's own way of doing the thing wins. One named by its command (`/fix`) goes in whatever
|
|
91
|
+
* was shown before, and whatever the switch says: the user asked for it.
|
|
92
|
+
*/
|
|
93
|
+
function guideDue(db, e, now, taught) {
|
|
94
|
+
const name = e.guide ?? (!taught && autoGuides(db) ? matchGuide(e.prompt) : null);
|
|
95
|
+
if (!name || !firingGuides().some((g) => g.name === name)) return '';
|
|
96
|
+
const slug = `guide:${name}`;
|
|
97
|
+
if (!e.guide && db.prepare('SELECT 1 FROM session_injections WHERE session_id = ? AND slug = ?').get(e.sessionId, slug)) return '';
|
|
98
|
+
markInjected(db, e.sessionId, slug, now);
|
|
99
|
+
return renderGuide(name);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* An edit nothing has checked is not done, whatever the reply says. The chat says which files the turn edited after
|
|
104
|
+
* the last of the project's declared checks ran, and which those checks are; the fact is put in front of the model
|
|
105
|
+
* and the turn goes on. An edit made through the shell is not seen, and a harness that says nothing of edits is
|
|
106
|
+
* left alone.
|
|
107
|
+
*/
|
|
108
|
+
function unchecked(db, e) {
|
|
109
|
+
if (e.edited.length === 0 || !autoGuides(db)) return '';
|
|
110
|
+
const first = e.edited.slice(0, 3);
|
|
111
|
+
const rest = e.edited.length > 3 ? `${e.edited.length - 3} more` : first.length > 1 ? first.pop() : null;
|
|
112
|
+
const shown = rest ? `${first.join(', ')} and ${rest}` : first[0];
|
|
113
|
+
const were = e.edited.length === 1 ? 'was' : 'were';
|
|
114
|
+
const them = e.edited.length === 1 ? 'it' : 'them';
|
|
115
|
+
const next =
|
|
116
|
+
e.checks.length > 0
|
|
117
|
+
? `nothing has checked ${them} since. The project's check is ${e.checks.map((c) => `\`${c}\``).join(' and ')} — run it and say what it showed, or say why it does not apply.`
|
|
118
|
+
: 'nothing ran after. This project declares no check — run what proves the change (the reproduction, or the test you wrote), or say why nothing does.';
|
|
119
|
+
return `<check>\nNot done yet: ${shown} ${were} edited and ${next}\n</check>`;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const HANDLERS = {
|
|
123
|
+
'session-start'(db, e, now) {
|
|
124
|
+
ensureSession(db, { id: e.sessionId, cwd: e.cwd, transcriptPath: e.transcriptPath, now });
|
|
125
|
+
// A fresh start wipes the cards from context; forgetting they were shown lets them come back.
|
|
126
|
+
if (e.source === 'compact' || e.source === 'new') clearInjections(db, e.sessionId);
|
|
127
|
+
|
|
128
|
+
if (shouldRun(db, { event: 'session-start', now })) spawnDetached(['scribe', 'run']);
|
|
129
|
+
if (sessionsAwaitingDream(db, now, SESSIONS_TO_DREAM).length >= SESSIONS_TO_DREAM) spawnDetached(['dream', 'run']);
|
|
130
|
+
|
|
131
|
+
const last = getMeta(db, 'last_backup');
|
|
132
|
+
if (!last || Date.parse(now) - Date.parse(last) > BACKUP_EVERY_MS) {
|
|
133
|
+
try {
|
|
134
|
+
backup(db, new Date(now));
|
|
135
|
+
} catch (cause) {
|
|
136
|
+
// Housekeeping: a snapshot that cannot be written costs the backup, never the session its memory. The block says it instead.
|
|
137
|
+
setMeta(db, 'backup.failed', String(cause.message).slice(0, 200));
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
try {
|
|
141
|
+
pruneStates(now);
|
|
142
|
+
} catch (cause) {
|
|
143
|
+
// Housekeeping too: a saved session that cannot be let go stays, and is said in the hook log, never to the session starting.
|
|
144
|
+
logFailure('session-start prune', cause);
|
|
145
|
+
}
|
|
146
|
+
try {
|
|
147
|
+
keepScratch(db, now);
|
|
148
|
+
} catch (cause) {
|
|
149
|
+
// And this: scratch that cannot be made or tidied is said in the hook log; the session still gets its memory.
|
|
150
|
+
logFailure('session-start scratch', cause);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return prime(db, { now });
|
|
154
|
+
},
|
|
155
|
+
|
|
156
|
+
prompt(db, e, now) {
|
|
157
|
+
ensureSession(db, { id: e.sessionId, cwd: e.cwd, transcriptPath: e.transcriptPath, now });
|
|
158
|
+
if (recordTurn(db, { sessionId: e.sessionId, text: e.prompt, now }) === null) return '';
|
|
159
|
+
|
|
160
|
+
const shown = new Set(injectedSlugs(db, e.sessionId));
|
|
161
|
+
const cards = [];
|
|
162
|
+
for (const slug of detect(db, e.prompt)) {
|
|
163
|
+
touch(db, slug, now);
|
|
164
|
+
// Every mention is stamped, not only the first: the project named last is the one the session is about, also when its card was shown before.
|
|
165
|
+
markInjected(db, e.sessionId, slug, now);
|
|
166
|
+
if (shown.has(slug)) continue;
|
|
167
|
+
cards.push(card(db, slug, { now }));
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const asked = claim(db, { sessionId: e.sessionId, text: e.prompt, scopes: scopesOf(db, e.sessionId), now });
|
|
171
|
+
if (asked.length > 0) {
|
|
172
|
+
cards.push(`The user taught a workflow for what they are asking — follow it exactly, in order:\n${asked.map(renderWorkflow).join('\n')}`);
|
|
173
|
+
}
|
|
174
|
+
const guide = guideDue(db, e, now, asked.length > 0);
|
|
175
|
+
if (guide) cards.push(guide);
|
|
176
|
+
|
|
177
|
+
const size = sizeNudge(db, e, now);
|
|
178
|
+
if (size) cards.push(size);
|
|
179
|
+
return cards.join('\n');
|
|
180
|
+
},
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* The gate. A shell command that is the thing a workflow is about does not run until that
|
|
184
|
+
* workflow's steps are in front of whoever is running it. Once per session per agent: the point
|
|
185
|
+
* is to put the steps there at the moment of action, not to argue.
|
|
186
|
+
*/
|
|
187
|
+
'pre-tool'(db, e, now) {
|
|
188
|
+
// A question on its way to the user: what memory holds close to it is read first, and holds it back once.
|
|
189
|
+
if (e.toolName === 'ask') {
|
|
190
|
+
ensureSession(db, { id: e.sessionId, cwd: e.cwd, transcriptPath: e.transcriptPath, now });
|
|
191
|
+
const known = recallBeforeAsking(db, { sessionId: e.sessionId, agentId: e.agentId, asked: e.question, now });
|
|
192
|
+
return known.length > 0 ? deny(`Not asked yet: ${alreadyKnown(known)} If none does, ask again.`) : '';
|
|
193
|
+
}
|
|
194
|
+
if (e.toolName !== 'bash' || !e.command) return '';
|
|
195
|
+
// Teaching or reading a workflow names its own cue; `sumo` must never be gated by what it manages — and nothing else rides through on it.
|
|
196
|
+
const judged = withoutSumoCalls(e.command);
|
|
197
|
+
if (!judged) return '';
|
|
198
|
+
ensureSession(db, { id: e.sessionId, cwd: e.cwd, transcriptPath: e.transcriptPath, now });
|
|
199
|
+
|
|
200
|
+
const due = claim(db, { sessionId: e.sessionId, agentId: e.agentId, text: judged, scopes: [...scopesOf(db, e.sessionId), ...(e.project ? [`project:${e.project}`] : [])], forCommand: true, now });
|
|
201
|
+
if (due.length === 0) return '';
|
|
202
|
+
return deny(
|
|
203
|
+
`Not yet. The user taught a workflow for exactly this, and it has not been followed in this session:\n${due.map(renderWorkflow).join('\n')}\n` +
|
|
204
|
+
'Do its steps in order — some come before this command — then run the command again.',
|
|
205
|
+
);
|
|
206
|
+
},
|
|
207
|
+
|
|
208
|
+
stop(db, e, now) {
|
|
209
|
+
ensureSession(db, { id: e.sessionId, cwd: e.cwd, transcriptPath: e.transcriptPath, now });
|
|
210
|
+
if (shouldRun(db, { event: 'stop', now })) spawnDetached(['scribe', 'run']);
|
|
211
|
+
|
|
212
|
+
// The other gates: a turn that ends on an edit nothing checked, or by asking the user something memory may
|
|
213
|
+
// already hold. Already continuing because of one → whatever the turn ends on now goes to the user.
|
|
214
|
+
if (e.stopHookActive) return '';
|
|
215
|
+
const known = e.reply ? recallBeforeAsking(db, { sessionId: e.sessionId, asked: closingQuestions(e.reply), now }) : [];
|
|
216
|
+
const held = [unchecked(db, e), known.length > 0 ? `Before the user answers that: ${alreadyKnown(known)} If none does, the question stands — say so in one line.` : ''].filter(Boolean);
|
|
217
|
+
return held.length > 0 ? JSON.stringify({ context: held.join('\n') }) : '';
|
|
218
|
+
},
|
|
219
|
+
|
|
220
|
+
'session-end'(db, e, now) {
|
|
221
|
+
ensureSession(db, { id: e.sessionId, cwd: e.cwd, transcriptPath: e.transcriptPath, now });
|
|
222
|
+
endSession(db, e.sessionId, now);
|
|
223
|
+
if (shouldRun(db, { event: 'session-end', now })) spawnDetached(['scribe', 'run']);
|
|
224
|
+
return '';
|
|
225
|
+
},
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
/** One event, in process: the guard first, then the handler. Throws only for an unknown event or a payload with no session. */
|
|
229
|
+
export function handleEvent(db, event, payload, now = new Date().toISOString()) {
|
|
230
|
+
const handler = HANDLERS[event];
|
|
231
|
+
if (!handler) throw new Error(`no handler for ${event}`);
|
|
232
|
+
const e = fieldsOf(payload);
|
|
233
|
+
if (!e.sessionId) throw new Error('the event had no session id');
|
|
234
|
+
const refused = event === 'pre-tool' ? earlyRefusal(e) : '';
|
|
235
|
+
if (refused) return deny(refused);
|
|
236
|
+
return handler(db, e, now);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** What went wrong, in logs/hook.log. If even the log cannot be written there is nothing left to do but stay out of the way. */
|
|
240
|
+
function logFailure(what, cause) {
|
|
241
|
+
try {
|
|
242
|
+
mkdirSync(paths().logs, { recursive: true, mode: 0o700 });
|
|
243
|
+
appendFileSync(join(paths().logs, 'hook.log'), `${new Date().toISOString()} ${what}: ${cause.stack ?? cause}\n`);
|
|
244
|
+
} catch {
|
|
245
|
+
// Said above.
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* One event from outside the process, JSON on stdin. It never throws and never
|
|
251
|
+
* exits non-zero: memory is a convenience, and a convenience that can break the
|
|
252
|
+
* session it serves is worse than none. Whatever goes wrong is written to
|
|
253
|
+
* logs/hook.log and the session simply carries on without this contribution.
|
|
254
|
+
*/
|
|
255
|
+
export function runHook(event, stdin) {
|
|
256
|
+
let db = null;
|
|
257
|
+
try {
|
|
258
|
+
const payload = JSON.parse(stdin || '{}');
|
|
259
|
+
// The guard needs no database, and a database that cannot be opened must not stop it.
|
|
260
|
+
const refused = event === 'pre-tool' ? earlyRefusal(fieldsOf(payload)) : '';
|
|
261
|
+
if (refused) return deny(refused);
|
|
262
|
+
db = openDb();
|
|
263
|
+
return handleEvent(db, event, payload);
|
|
264
|
+
} catch (cause) {
|
|
265
|
+
logFailure(event, cause);
|
|
266
|
+
return '';
|
|
267
|
+
} finally {
|
|
268
|
+
db?.close();
|
|
269
|
+
}
|
|
270
|
+
}
|
package/src/images.mjs
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
2
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
3
|
+
import { isAbsolute } from 'node:path';
|
|
4
|
+
import { promisify } from 'node:util';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Pictures for the chat, as the API takes them: the media type, told from the
|
|
8
|
+
* first bytes rather than the name, and the bytes in base64. They come from
|
|
9
|
+
* the clipboard — macOS's, read with osascript — or from files dropped on the
|
|
10
|
+
* terminal, which arrive pasted as their paths.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** The most the API takes of one image, base64 encoded. */
|
|
14
|
+
export const MAX_IMAGE_BYTES = 10_000_000;
|
|
15
|
+
const NAMES = /\.(png|jpe?g|gif|webp)$/i;
|
|
16
|
+
|
|
17
|
+
const KINDS = [
|
|
18
|
+
['image/png', (b) => b.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex'))],
|
|
19
|
+
['image/jpeg', (b) => b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff],
|
|
20
|
+
['image/gif', (b) => /^GIF8[79]a/.test(b.toString('latin1', 0, 6))],
|
|
21
|
+
['image/webp', (b) => b.toString('latin1', 0, 4) === 'RIFF' && b.toString('latin1', 8, 12) === 'WEBP'],
|
|
22
|
+
];
|
|
23
|
+
|
|
24
|
+
/** Bytes as an image to send, or null when they are none the API reads; one too big to send is said back. */
|
|
25
|
+
function imageOf(bytes) {
|
|
26
|
+
const mediaType = KINDS.find(([, is]) => is(bytes))?.[0];
|
|
27
|
+
if (!mediaType) return null;
|
|
28
|
+
tooBig(bytes.length);
|
|
29
|
+
return { mediaType, data: bytes.toString('base64') };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Said from the raw size, so a file too big to send is never read whole or encoded. */
|
|
33
|
+
function tooBig(size) {
|
|
34
|
+
const encoded = Math.ceil(size / 3) * 4;
|
|
35
|
+
if (encoded > MAX_IMAGE_BYTES) throw new Error(`that image is too big — ${(encoded / 1e6).toFixed(1)} MB encoded, and the API takes ${MAX_IMAGE_BYTES / 1e6} MB`);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** What osascript prints for the clipboard as PNG: `«data PNGf89504E47…»`. It fails when there is no image on it. */
|
|
39
|
+
const readMacClipboard = async () => (await promisify(execFile)('osascript', ['-e', 'the clipboard as «class PNGf»'], { maxBuffer: 4 * MAX_IMAGE_BYTES, timeout: 10_000 })).stdout;
|
|
40
|
+
|
|
41
|
+
/** The image on the clipboard, or null when there is none. `read` is swapped in tests. */
|
|
42
|
+
export async function clipboardImage(read = readMacClipboard) {
|
|
43
|
+
let printed;
|
|
44
|
+
try {
|
|
45
|
+
printed = await read();
|
|
46
|
+
} catch (cause) {
|
|
47
|
+
// Too much to read is an image too big to send, not an empty clipboard.
|
|
48
|
+
if (cause.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') throw new Error(`that image is too big — the API takes ${MAX_IMAGE_BYTES / 1e6} MB encoded`);
|
|
49
|
+
// No osascript is no Mac, not an empty clipboard: say what does work here.
|
|
50
|
+
if (cause.code === 'ENOENT') throw new Error('pasting an image from the clipboard needs macOS — drop the image file on the box instead');
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
const hex = /«data PNGf([0-9A-Fa-f]+)»/.exec(printed)?.[1];
|
|
54
|
+
return hex ? imageOf(Buffer.from(hex, 'hex')) : null;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The words of a paste the way a terminal writes dropped paths: a space or quote kept with a backslash, or the whole path in quotes.
|
|
59
|
+
* Only a plain space, tab or line end parts them — a screenshot's name holds a narrow no-break space that no terminal escapes.
|
|
60
|
+
*/
|
|
61
|
+
const wordsOf = (text) => (text.trim().match(/'[^']*'|"[^"]*"|(?:\\.|[^ \t\r\n\\'"])+/g) ?? []).map((w) => (/^['"]/.test(w) ? w.slice(1, -1) : w.replace(/\\(.)/g, '$1')));
|
|
62
|
+
|
|
63
|
+
/** The images a paste is, when every word of it is the path of an image file; null when it is text. */
|
|
64
|
+
export function droppedImages(text) {
|
|
65
|
+
const paths = wordsOf(text);
|
|
66
|
+
const stats = paths.map((p) => (isAbsolute(p) && NAMES.test(p) ? statSync(p, { throwIfNoEntry: false }) : undefined));
|
|
67
|
+
if (paths.length === 0 || !stats.every((s) => s?.isFile())) return null;
|
|
68
|
+
for (const s of stats) tooBig(s.size);
|
|
69
|
+
const images = paths.map((p) => imageOf(readFileSync(p)));
|
|
70
|
+
return images.every(Boolean) ? images : null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The commands that put text on the clipboard, by platform: the first one that is there takes it. */
|
|
74
|
+
const COPIERS = process.platform === 'darwin' ? [['pbcopy']] : [['wl-copy'], ['xclip', '-selection', 'clipboard'], ['xsel', '--clipboard', '--input']];
|
|
75
|
+
|
|
76
|
+
/** Text to the clipboard, exactly as given. False when no command here takes it — the caller has the terminal to ask instead. */
|
|
77
|
+
export async function copyText(text, copiers = COPIERS) {
|
|
78
|
+
for (const [command, ...args] of copiers) {
|
|
79
|
+
const taken = await new Promise((resolve) => {
|
|
80
|
+
const child = spawn(command, args, { stdio: ['pipe', 'ignore', 'ignore'] });
|
|
81
|
+
child.on('error', () => resolve(false));
|
|
82
|
+
child.on('close', (status) => resolve(status === 0));
|
|
83
|
+
child.stdin.on('error', () => {});
|
|
84
|
+
child.stdin.end(text);
|
|
85
|
+
});
|
|
86
|
+
if (taken) return true;
|
|
87
|
+
}
|
|
88
|
+
return false;
|
|
89
|
+
}
|