switch-ext-kit 0.0.0-stage → 0.2.1

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/src/laptop.ts ADDED
@@ -0,0 +1,475 @@
1
+ // The user's own laptop, the machine they work at: nothing heavy or interruptive of the agent's
2
+ // runs there while another machine can do it, even while they've stepped away. Which machine that
3
+ // is, is data: its host lists `personal` in what it provides, and an extension sees it in
4
+ // SWITCH_PROVIDES. Ported from Switchboard's laptop guard (sb guard, the macOS appendage's
5
+ // personal.rs): it reads what a command line runs, with the variables it sets followed, into `sh
6
+ // -c`, `eval` and the scripts it runs, and stand-ins first on PATH refuse what a script runs deeper
7
+ // down.
8
+ import {
9
+ chmodSync,
10
+ existsSync,
11
+ mkdirSync,
12
+ readFileSync,
13
+ renameSync,
14
+ statSync,
15
+ writeFileSync,
16
+ } from "node:fs"
17
+ import { homedir } from "node:os"
18
+ import path from "node:path"
19
+
20
+ import { simpleCommands } from "./shell.ts"
21
+
22
+ export { simpleCommands } from "./shell.ts"
23
+
24
+ /** What a machine provides when it's the user's own laptop. */
25
+ export const PERSONAL = "personal"
26
+
27
+ /** The argument, and the variable leading a shell command, that carries the user's asking. */
28
+ export const PERSON_ASKED = "person_asked"
29
+ const ASKED_VAR = "PERSON_ASKED"
30
+ const ASKED_MIN = 8
31
+
32
+ /** What this extension's machine provides, as its host said. */
33
+ export const provides = (): readonly string[] =>
34
+ (process.env.SWITCH_PROVIDES ?? "").split(",").filter((p) => p !== "")
35
+
36
+ /** Whether this extension runs on the user's own laptop. */
37
+ export const personal = (): boolean => provides().includes(PERSONAL)
38
+
39
+ /** Whether `said` is the user's words, enough to be theirs. */
40
+ export const asked = (said: unknown): boolean =>
41
+ typeof said === "string" && said.trim().length >= ASKED_MIN
42
+
43
+ /** Programs that make a machine hot or slow, by the name they're run by. */
44
+ const HEAVY = new Set([
45
+ "blender",
46
+ "ffmpeg",
47
+ "xcodebuild",
48
+ "simctl",
49
+ "bambustudio",
50
+ "orcaslicer",
51
+ "prusaslicer",
52
+ "remotion",
53
+ ])
54
+ /** What `cargo` or `swift` does when it builds. */
55
+ const BUILDS = new Set(["build", "test", "clippy", "check", "run", "bench", "nextest", "install"])
56
+ const WRAPPERS = new Set([
57
+ "sudo",
58
+ "nice",
59
+ "env",
60
+ "time",
61
+ "nohup",
62
+ "exec",
63
+ "caffeinate",
64
+ "xcrun",
65
+ "taskpolicy",
66
+ "timeout",
67
+ "command",
68
+ "arch",
69
+ "noglob",
70
+ ])
71
+ const INTO = new Set(["sh", "zsh", "bash", "dash", "open"])
72
+ const SHELLS = new Set(["sh", "bash", "zsh", "dash"])
73
+ /** Flags that only ask a program what it is or can do. */
74
+ const LIGHT = new Set([
75
+ "--version",
76
+ "-version",
77
+ "--help",
78
+ "-help",
79
+ "-h",
80
+ "--list",
81
+ "-list",
82
+ "-showsdks",
83
+ ])
84
+ /** What `xcrun simctl` does that boots nothing. */
85
+ const SIMCTL_LIGHT = new Set(["list", "shutdown", "delete", "help", "getenv", "runtime"])
86
+ const INTERPRETERS = new Set([
87
+ "python",
88
+ "python3",
89
+ "node",
90
+ "bun",
91
+ "deno",
92
+ "ruby",
93
+ "perl",
94
+ "osascript",
95
+ "uv",
96
+ ])
97
+ const DEPTH = 3
98
+ const SCRIPT_BYTES = 512 * 1024
99
+
100
+ const nameOf = (word: string) => word.split("/").at(-1) ?? word
101
+
102
+ const isOption = (w: string) => w.startsWith("-") || w.startsWith("+")
103
+ const isNumber = (w: string) => w !== "" && !Number.isNaN(Number(w))
104
+
105
+ /** A shell assignment's name and value (`B=/Applications/…`). */
106
+ const assignment = (word: string): readonly [string, string] | null => {
107
+ const at = word.indexOf("=")
108
+ if (at <= 0) {
109
+ return null
110
+ }
111
+ const name = word.slice(0, at)
112
+ return /^[A-Za-z_][A-Za-z0-9_]*$/u.test(name) ? [name, word.slice(at + 1)] : null
113
+ }
114
+
115
+ const substitute = (word: string, vars: ReadonlyMap<string, string>) =>
116
+ word.includes("$")
117
+ ? word.replaceAll(
118
+ /\$\{(?<braced>[A-Za-z_][A-Za-z0-9_]*)\}|\$(?<bare>[A-Za-z_][A-Za-z0-9_]*)/gu,
119
+ (all, a: string | undefined, b: string | undefined) => vars.get(a ?? b ?? "") ?? all,
120
+ )
121
+ : word
122
+
123
+ /** The heavy program one command runs, past assignments, options and wrappers, into shells. */
124
+ const heavyRun = (words: readonly string[]): string | null => {
125
+ // `command -v ffmpeg` only asks where it is.
126
+ for (let i = 0; i + 1 < words.length; i += 1) {
127
+ if (nameOf(words[i] ?? "") === "command" && (words[i + 1] === "-v" || words[i + 1] === "-V")) {
128
+ return null
129
+ }
130
+ }
131
+ const rest = words.filter((w) => !isOption(w) && !isNumber(w))
132
+ let at = 0
133
+ while (at < rest.length && assignment(rest[at] ?? "") !== null) {
134
+ at += 1
135
+ }
136
+ for (; at < rest.length; at += 1) {
137
+ const name = nameOf(rest[at] ?? "")
138
+ .toLowerCase()
139
+ .replace(/\.app$/u, "")
140
+ if (HEAVY.has(name)) {
141
+ return name
142
+ }
143
+ if (name === "cargo" || name === "swift") {
144
+ const sub = rest[at + 1] ?? ""
145
+ return BUILDS.has(sub) ? `${name} ${sub}` : null
146
+ }
147
+ if (!WRAPPERS.has(name) && !INTO.has(name)) {
148
+ return null
149
+ }
150
+ }
151
+ return null
152
+ }
153
+
154
+ /** Whether what a heavy program was asked to do is light anyway. */
155
+ const light = (found: string, words: readonly string[]) => {
156
+ if (found.startsWith("cargo") || found.startsWith("swift")) {
157
+ return false
158
+ }
159
+ if (found === "simctl") {
160
+ const at = words.findIndex((w) => nameOf(w) === "simctl")
161
+ return SIMCTL_LIGHT.has(words[at + 1] ?? "")
162
+ }
163
+ return words.some((w) => LIGHT.has(w))
164
+ }
165
+
166
+ /** The bodies of a command line's here documents. */
167
+ const hereDocuments = (line: string) => {
168
+ const bodies: string[] = []
169
+ for (const found of line.matchAll(/<<-?\s*['"]?(?<delimiter>[A-Za-z_][A-Za-z0-9_]*)['"]?/gu)) {
170
+ const delimiter = found.groups?.delimiter ?? ""
171
+ const after = line.slice((found.index ?? 0) + found[0].length)
172
+ const start = after.indexOf("\n")
173
+ if (start === -1) {
174
+ continue
175
+ }
176
+ const body: string[] = []
177
+ for (const l of after.slice(start + 1).split("\n")) {
178
+ if (l.replace(/^\t+/u, "") === delimiter) {
179
+ break
180
+ }
181
+ body.push(l)
182
+ }
183
+ bodies.push(body.join("\n"))
184
+ }
185
+ return bodies
186
+ }
187
+
188
+ /** The heavy programs a script of another language names as strings. */
189
+ const named = (text: string) => {
190
+ const program =
191
+ /["'](?:[^"'\s]*\/)?(?<name>blender|ffmpeg|xcodebuild|bambustudio|orcaslicer|prusaslicer|remotion)(?:\.app)?["'\s]/iu.exec(
192
+ text,
193
+ )
194
+ if (program) {
195
+ return (program.groups?.name ?? "").toLowerCase()
196
+ }
197
+ const cargo =
198
+ /["'](?<p1>cargo|swift)["']\s*,\s*["'](?<s1>build|test|clippy|check|run|bench|nextest|install)["']|["'](?<p2>cargo|swift) (?<s2>build|test|clippy|check|run|bench|nextest|install)\b/u.exec(
199
+ text,
200
+ )
201
+ const g = cargo?.groups
202
+ return g ? `${g.p1 ?? g.p2 ?? "cargo"} ${g.s1 ?? g.s2 ?? "build"}` : null
203
+ }
204
+
205
+ const shebangShell = (text: string) => {
206
+ const first = text.split("\n")[0] ?? ""
207
+ return first.startsWith("#!") && first.split(/[/\s]/u).some((w) => SHELLS.has(w))
208
+ }
209
+
210
+ type Script =
211
+ | { readonly kind: "file"; readonly file: string; readonly shell: boolean | null }
212
+ | { readonly kind: "code"; readonly code: string }
213
+ | { readonly kind: "stdin" }
214
+
215
+ /** The script a command runs: what a shell or an interpreter is given, or the command as a path. */
216
+ const scriptOf = (words: readonly string[]): Script | null => {
217
+ for (let at = 0; at < words.length; at += 1) {
218
+ const word = words[at] ?? ""
219
+ const program = nameOf(word)
220
+ if (isOption(word) || isNumber(word) || WRAPPERS.has(program) || assignment(word) !== null) {
221
+ continue
222
+ }
223
+ const rest = words.slice(at + 1)
224
+ if (SHELLS.has(program) || program === "source" || program === ".") {
225
+ const file = rest.find((w) => !w.startsWith("-"))
226
+ return file === undefined ? null : { kind: "file", file, shell: true }
227
+ }
228
+ if (INTERPRETERS.has(program) || program.startsWith("python3.")) {
229
+ const c = rest.findIndex((w) => w === "-c" || w === "-e")
230
+ const code = c === -1 ? undefined : rest[c + 1]
231
+ if (code !== undefined) {
232
+ return { kind: "code", code }
233
+ }
234
+ // `uv run x.py`, `bun run x.ts`: past the subcommand to the file.
235
+ const file = rest.find((w) => !w.startsWith("-") && (w.includes(".") || w.includes("/")))
236
+ return file === undefined ? { kind: "stdin" } : { kind: "file", file, shell: false }
237
+ }
238
+ return word.includes("/") ? { kind: "file", file: word, shell: null } : null
239
+ }
240
+ return null
241
+ }
242
+
243
+ /** Reads a script, if it's a file of a size worth reading. */
244
+ export type Reader = (file: string) => string | null
245
+
246
+ const readLocal: Reader = (file) => {
247
+ try {
248
+ const s = statSync(file)
249
+ return s.isFile() && s.size <= SCRIPT_BYTES ? readFileSync(file, "utf-8") : null
250
+ } catch {
251
+ return null
252
+ }
253
+ }
254
+
255
+ const expand = (p: string, dir: string, home: string) => {
256
+ if (p === "~") {
257
+ return home
258
+ }
259
+ if (p.startsWith("~/")) {
260
+ return path.join(home, p.slice(2))
261
+ }
262
+ return path.resolve(dir, p)
263
+ }
264
+
265
+ interface Walk {
266
+ readonly home: string
267
+ readonly read: Reader
268
+ }
269
+
270
+ const inScript = (
271
+ words: readonly string[],
272
+ dir: string,
273
+ line: string,
274
+ vars: Map<string, string>,
275
+ depth: number,
276
+ w: Walk,
277
+ ): string | null => {
278
+ const s = scriptOf(words)
279
+ if (s === null) {
280
+ return null
281
+ }
282
+ let text = ""
283
+ let said: string | null = null
284
+ let shell = false
285
+ if (s.kind === "code") {
286
+ text = s.code
287
+ } else if (s.kind === "stdin") {
288
+ text = hereDocuments(line).join("\n")
289
+ } else {
290
+ const file = expand(s.file, dir, w.home)
291
+ // Not there yet: the same command line may be writing it, with a here document.
292
+ text = w.read(file) ?? (existsSync(file) ? "" : hereDocuments(line).join("\n"))
293
+ said = s.file
294
+ shell = s.shell ?? shebangShell(text)
295
+ }
296
+ const found = shell ? runs(text, dir, new Map(vars), depth + 1, w) : named(text)
297
+ if (found === null) {
298
+ return null
299
+ }
300
+ return said !== null && !found.includes(", in ") ? `${found}, in ${said}` : found
301
+ }
302
+
303
+ const DECLARE = new Set(["export", "local", "readonly", "declare", "typeset"])
304
+
305
+ /**
306
+ * Takes a command's assignments into `vars`: alone, they set what later `$NAME`s stand for;
307
+ * leading, they're its environment. The words left to run, none for a declaration.
308
+ */
309
+ const assign = (all: readonly string[], vars: Map<string, string>) => {
310
+ let at = 0
311
+ for (let a = assignment(all[at] ?? ""); a !== null; a = assignment(all[at] ?? "")) {
312
+ vars.set(a[0], substitute(a[1], vars))
313
+ at += 1
314
+ }
315
+ if (DECLARE.has(all[at] ?? "")) {
316
+ for (const word of all.slice(at + 1)) {
317
+ const a = assignment(word)
318
+ if (a !== null) {
319
+ vars.set(a[0], substitute(a[1], vars))
320
+ }
321
+ }
322
+ return []
323
+ }
324
+ return all.slice(at).map((x) => substitute(x, vars))
325
+ }
326
+
327
+ /** What a shell's `-c` runs, among its own options before what it's given. */
328
+ const dashC = (rest: readonly string[]) => {
329
+ const options = rest.findIndex((x) => !isOption(x))
330
+ const own = options === -1 ? rest : rest.slice(0, options)
331
+ const at = own.findIndex(
332
+ (x) => x === "-c" || (!x.startsWith("--") && x.startsWith("-") && x.endsWith("c")),
333
+ )
334
+ return at === -1 ? null : (rest[at + 1] ?? "")
335
+ }
336
+
337
+ interface Here {
338
+ dir: string
339
+ readonly line: string
340
+ readonly vars: Map<string, string>
341
+ readonly depth: number
342
+ readonly w: Walk
343
+ }
344
+
345
+ /** What one command runs that's heavy, following it into shells, eval and scripts. */
346
+ const runOne = (words: readonly string[], h: Here): string | null => {
347
+ const [program = "", ...rest] = words
348
+ const name = nameOf(program)
349
+ if (name === "cd" || name === "pushd") {
350
+ const to = rest.find((x) => !x.startsWith("-"))
351
+ if (to !== undefined) {
352
+ h.dir = expand(to, h.dir, h.w.home)
353
+ } else if (rest.length === 0) {
354
+ h.dir = h.w.home
355
+ }
356
+ return null
357
+ }
358
+ const inner = SHELLS.has(name) ? dashC(rest) : null
359
+ if (inner !== null) {
360
+ return runs(inner, h.dir, h.vars, h.depth, h.w)
361
+ }
362
+ if (name === "eval") {
363
+ return runs(rest.join(" "), h.dir, h.vars, h.depth, h.w)
364
+ }
365
+ const found = heavyRun(words)
366
+ if (found !== null) {
367
+ return light(found, words) ? null : found
368
+ }
369
+ return h.depth < DEPTH ? inScript(words, h.dir, h.line, h.vars, h.depth, h.w) : null
370
+ }
371
+
372
+ const runs = (
373
+ line: string,
374
+ dir: string,
375
+ vars: Map<string, string>,
376
+ depth: number,
377
+ w: Walk,
378
+ ): string | null => {
379
+ const h: Here = { dir, line, vars, depth, w }
380
+ for (const all of simpleCommands(line)) {
381
+ const words = assign(all, vars)
382
+ const found = words.length > 0 ? runOne(words, h) : null
383
+ if (found !== null) {
384
+ return found
385
+ }
386
+ }
387
+ return null
388
+ }
389
+
390
+ /** The words of a leading `PERSON_ASKED='…'`: the user asked for exactly this, here. */
391
+ export const personAsked = (command: string): string | null => {
392
+ for (const words of simpleCommands(command)) {
393
+ for (const word of words) {
394
+ const a = assignment(word)
395
+ if (a !== null && a[0] === ASKED_VAR && asked(a[1])) {
396
+ return a[1]
397
+ }
398
+ }
399
+ }
400
+ return null
401
+ }
402
+
403
+ /**
404
+ * The heavy work a shell command line runs, as a phrase ("blender", "cargo test, in build.sh"), or
405
+ * null: builds and tests, Blender, encoders, simulators, slicers. Null too when it carries the
406
+ * user's asking (`PERSON_ASKED`).
407
+ */
408
+ export const heavy = (
409
+ command: string,
410
+ options: { readonly cwd?: string; readonly home?: string; readonly read?: Reader } = {},
411
+ ): string | null => {
412
+ if (personAsked(command) !== null) {
413
+ return null
414
+ }
415
+ const home = options.home ?? homedir()
416
+ return runs(command, options.cwd ?? home, new Map(), 0, { home, read: options.read ?? readLocal })
417
+ }
418
+
419
+ const listed = (elsewhere: readonly string[]) =>
420
+ elsewhere.length > 0 ? elsewhere.join(" or ") : "a machine that isn't the user's laptop"
421
+
422
+ /**
423
+ * Why a call was refused on the user's laptop (`what`: "run blender", "drive its browser"), and
424
+ * where to do it instead.
425
+ */
426
+ export const refusal = (what: string, elsewhere: readonly string[] = []): string =>
427
+ `This is the user's own laptop, the machine they work at, so the agent doesn't ${what} here, even while they've stepped away. Do it on ${listed(elsewhere)} instead (its macos extension's exec, files copied there with rsync first). Only when the user asked for exactly this on this machine, call again with ${PERSON_ASKED} (a shell command: led by ${ASKED_VAR}='…'): their words, and when they said them.`
428
+
429
+ const SHIMS = ["cargo", "swift", "xcodebuild", "xcrun", "ffmpeg"]
430
+
431
+ const shq = (text: string) => `'${text.replaceAll("'", "'\\''")}'`
432
+
433
+ /**
434
+ * Writes PATH stand-ins into `dir` for what a script runs to build, test or encode: each refuses
435
+ * that, unless PERSON_ASKED is set, and runs the real program (on PATH past `dir`) for the rest.
436
+ * Returns `dir`, to put first on PATH.
437
+ */
438
+ export const standIns = (dir: string, elsewhere: readonly string[] = []): string => {
439
+ mkdirSync(dir, { recursive: true })
440
+ const said = refusal("run $heavy, even from a script,", elsewhere)
441
+ const script = `#!/bin/sh
442
+ # Put first on PATH on the user's own laptop, so heavy work refuses even from inside a script.
443
+ name=\${0##*/}
444
+ first=
445
+ for arg in "$@"; do case "$arg" in -*|+*) ;; *) first=$arg; break;; esac; done
446
+ heavy=
447
+ case "$name" in
448
+ cargo|swift) case "$first" in build|test|clippy|check|run|bench|nextest|install) heavy="$name $first";; esac;;
449
+ xcrun) case "$first" in xcodebuild|simctl) heavy="$first";; esac;;
450
+ *) heavy=$name;;
451
+ esac
452
+ case "$*" in *--version*|*-version*|*--help*|*-showsdks*) heavy=;; esac
453
+ if [ "$name" = xcrun ] && [ "$first" = simctl ]; then
454
+ for arg in "$@"; do case "$arg" in list|shutdown|delete|help|getenv|runtime) heavy=; break;; esac; done
455
+ fi
456
+ if [ -n "$heavy" ] && [ \${#${ASKED_VAR}} -lt ${ASKED_MIN} ]; then
457
+ echo "${said.replaceAll('"', '\\"')}" >&2
458
+ exit 126
459
+ fi
460
+ here=${shq(dir)}
461
+ PATH=$(printf '%s' "$PATH" | tr ':' '\\n' | grep -vxF "$here" | paste -sd: -)
462
+ export PATH
463
+ exec "$name" "$@"
464
+ `
465
+ for (const name of SHIMS) {
466
+ const file = path.join(dir, name)
467
+ if (!existsSync(file) || readFileSync(file, "utf-8") !== script) {
468
+ const partial = path.join(dir, `.${name}.new`)
469
+ writeFileSync(partial, script)
470
+ chmodSync(partial, 0o755)
471
+ renameSync(partial, file)
472
+ }
473
+ }
474
+ return dir
475
+ }