pi-odd-worktree 3.2.0 → 3.4.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/README.md +3 -0
- package/extensions/odd-worktree-tools.ts +43 -3
- package/lib/bash-activity.js +405 -32
- package/lib/bash-design.js +8 -2
- package/lib/bash-inline-script.js +314 -0
- package/lib/file-card-resolver.js +4 -0
- package/lib/file-card.js +8 -0
- package/lib/jobs-card-resolver.js +139 -0
- package/lib/jobs-card.js +220 -0
- package/lib/skill-read-guard.js +397 -0
- package/package.json +1 -1
- package/tools/bash-activity.test.js +400 -35
- package/tools/bash-design.test.js +8 -8
- package/tools/jobs-card.test.js +292 -0
- package/tools/package-surface.test.js +15 -1
- package/tools/skill-read-guard.test.js +316 -0
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// The activity an INLINE script names: the program an interpreter is handed on its command
|
|
3
|
+
// line (`python3 -c '…'`, `node -e '…'`, `python3 - <<'PY' … PY`), read from its own text.
|
|
4
|
+
//
|
|
5
|
+
// A script is code, and code can do anything, so this reader answers only what the text
|
|
6
|
+
// itself proves and refuses everything else:
|
|
7
|
+
// * `destructive` — the text calls a deleting function (`os.remove`, `shutil.rmtree`,
|
|
8
|
+
// `fs.rmSync`, `.unlink(`). The call provably deletes whatever else it does.
|
|
9
|
+
// * `preparing` — the text writes, creates, renames or copies a file; the same
|
|
10
|
+
// build-up a `cat > file` already names.
|
|
11
|
+
// * `exploring` — the text imports only modules from a short list of read-only
|
|
12
|
+
// standard libraries, writes nothing and runs nothing.
|
|
13
|
+
// * `undefined` — anything else: a module outside the list (it runs code of its own),
|
|
14
|
+
// a shell-out, a network call, `eval`, a dynamic import, a flag this reader does not
|
|
15
|
+
// know. The card stays generic, as it always did.
|
|
16
|
+
//
|
|
17
|
+
// Pure: no filesystem, no process, no Pi. It reads a list of words and a string.
|
|
18
|
+
|
|
19
|
+
const PYTHON_PROGRAM = /^python(3(\.\d+)?)?$/;
|
|
20
|
+
const NODE_PROGRAM = /^nodejs?$/;
|
|
21
|
+
|
|
22
|
+
// Interpreter flags that change nothing about which code runs. A flag outside these lists
|
|
23
|
+
// ends the reading: `-m` runs a module, `-r`/`--import` load code first.
|
|
24
|
+
const PYTHON_PLAIN_FLAGS = new Set(['-I', '-B', '-u', '-E', '-S', '-s', '-O', '-OO', '-q', '-b', '-bb', '-d', '-v']);
|
|
25
|
+
const NODE_PLAIN_FLAGS = new Set([
|
|
26
|
+
'--no-warnings', '--no-deprecation', '--experimental-strip-types', '--experimental-vm-modules',
|
|
27
|
+
'--experimental-default-type=module', '--input-type=module', '--input-type=commonjs', '--enable-source-maps',
|
|
28
|
+
]);
|
|
29
|
+
|
|
30
|
+
// Standard-library modules that only read: parsing, text, hashing, dates and path math. A
|
|
31
|
+
// module outside the list may run any code on import, so a script that needs one stays
|
|
32
|
+
// generic.
|
|
33
|
+
const PYTHON_MODULES = new Set([
|
|
34
|
+
'json', 'sys', 're', 'os', 'pathlib', 'tomllib', 'collections', 'itertools', 'functools', 'textwrap',
|
|
35
|
+
'datetime', 'time', 'math', 'hashlib', 'base64', 'csv', 'glob', 'fnmatch', 'io', 'string', 'typing',
|
|
36
|
+
'operator', 'statistics', 'difflib', 'unicodedata', 'copy', 'enum', 'dataclasses', 'argparse',
|
|
37
|
+
'configparser', 'plistlib', 'struct', 'binascii', 'html', 'shlex', 'pprint', 'posixpath', 'uuid', 'yaml', 'toml', 'PIL',
|
|
38
|
+
]);
|
|
39
|
+
const NODE_MODULES = new Set([
|
|
40
|
+
'fs', 'fs/promises', 'path', 'os', 'util', 'url', 'assert', 'assert/strict', 'crypto', 'readline',
|
|
41
|
+
'stream', 'zlib', 'events', 'buffer', 'string_decoder', 'querystring', 'perf_hooks', 'timers',
|
|
42
|
+
]);
|
|
43
|
+
|
|
44
|
+
// What a script may not contain whatever it imports: running another program, evaluating
|
|
45
|
+
// text as code, loading code by name, talking to the network or a process, or hiding a name
|
|
46
|
+
// behind an alias. Read on the whole text, strings included: a script that merely MENTIONS one
|
|
47
|
+
// of these stays generic, which is the safe side.
|
|
48
|
+
const PYTHON_UNREADABLE = /\b(os\.(system|popen|exec\w*|spawn\w*|fork|forkpty|kill|killpg|putenv|startfile)|eval|exec|compile|__import__|importlib|getattr|setattr|globals|locals|breakpoint|signal|webbrowser|pty)\b|\bsubprocess\b|\bsocket\b|\bimport\s+\*|\bimport\s+(os|shutil)\s+as\b|,\s*(os|shutil)\s+as\b/;
|
|
49
|
+
const NODE_UNREADABLE = /\b(eval|Function|fetch|XMLHttpRequest|WebSocket|process\.(kill|binding|dlopen|chdir))\b|\.constructor\s*\(/;
|
|
50
|
+
|
|
51
|
+
// What the CODE of a script calls, read with every string literal and comment emptied, so a
|
|
52
|
+
// script that only prints the word is not a script that does it.
|
|
53
|
+
// A bare name counts only when it is called; a property access (`os.remove`, `fs.rmSync`) counts
|
|
54
|
+
// as written, because it may be aliased and called later.
|
|
55
|
+
const PYTHON_DELETES = /\bos\.(remove|unlink|rmdir|removedirs)\b|\bshutil\.rmtree\b|\b(rmtree|unlink|removedirs)\s*\(|\.(unlink|rmdir)\s*\(/;
|
|
56
|
+
const NODE_DELETES = /\.(rmSync|rmdirSync|unlinkSync)\b|\b(rmSync|rmdirSync|unlinkSync|rimraf)\s*\(|\.(rm|rmdir|unlink)\s*\(/;
|
|
57
|
+
|
|
58
|
+
const PYTHON_WRITES = /\.(write|writelines|write_text|write_bytes|touch|mkdir|rename|chmod|chown|symlink_to|hardlink_to|save|to_csv|to_json)\s*\(|\b(makedirs|os\.(rename|replace|mkdir|chmod|chown|symlink|link|truncate|utime)|shutil\.\w+)\b|\b(json|pickle|yaml|toml|plistlib)\.dump\s*\(/;
|
|
59
|
+
const NODE_WRITES = /\b(writeFile\w*|appendFile\w*|createWriteStream|mkdir\w*|copyFile\w*|cp\w*|rename\w*|chmod\w*|chown\w*|symlink\w*|link\w*|truncate\w*|utimes\w*|writeSync|write\w*)\s*\(|\.write\s*\(|\bWriteStream\b/;
|
|
60
|
+
|
|
61
|
+
// Names a script may take out of the filesystem module by destructuring: reads only.
|
|
62
|
+
const NODE_FS_READ_NAMES = new Set([
|
|
63
|
+
'readFileSync', 'readFile', 'readdirSync', 'readdir', 'existsSync', 'statSync', 'stat', 'lstatSync', 'lstat',
|
|
64
|
+
'readlinkSync', 'realpathSync', 'access', 'accessSync', 'promises',
|
|
65
|
+
]);
|
|
66
|
+
const PYTHON_OS_READ_NAMES = new Set(['path', 'environ', 'getcwd', 'listdir', 'walk', 'scandir', 'stat', 'sep', 'linesep', 'name']);
|
|
67
|
+
|
|
68
|
+
// A print is not a write: the two standard streams are what a read-only script talks to.
|
|
69
|
+
const PRINTING = /\bsys\.(stdout|stderr)\.write\s*\(|\bprocess\.(stdout|stderr)\.write\s*\(/g;
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* The text with the content of every string literal and comment emptied. An f-string and a
|
|
73
|
+
* template literal keep theirs: what sits inside their braces is code.
|
|
74
|
+
*/
|
|
75
|
+
function codeOf(language, text, keepModes = false) {
|
|
76
|
+
let out = '';
|
|
77
|
+
let index = 0;
|
|
78
|
+
while (index < text.length) {
|
|
79
|
+
const char = text[index];
|
|
80
|
+
if (language === 'python' && char === '#') {
|
|
81
|
+
while (index < text.length && text[index] !== '\n') index += 1;
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (language === 'node' && char === '/' && text[index + 1] === '/') {
|
|
85
|
+
while (index < text.length && text[index] !== '\n') index += 1;
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
if (language === 'node' && char === '/' && text[index + 1] === '*') {
|
|
89
|
+
const end = text.indexOf('*/', index + 2);
|
|
90
|
+
index = end < 0 ? text.length : end + 2;
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
if (char === '"' || char === "'" || char === '`') {
|
|
94
|
+
const triple = language === 'python' && text.startsWith(char.repeat(3), index);
|
|
95
|
+
const quote = triple ? char.repeat(3) : char;
|
|
96
|
+
let end = index + quote.length;
|
|
97
|
+
while (end < text.length && !text.startsWith(quote, end)) end += text[end] === '\\' ? 2 : 1;
|
|
98
|
+
const body = text.slice(index + quote.length, end);
|
|
99
|
+
// A short mode-shaped string (`'w'`, `'r+'`) is kept on request: it is what `open` reads.
|
|
100
|
+
const keep = char === '`' || (language === 'python' && /(^|[^a-z0-9_])(rf|fr|f)$/i.test(out.slice(-3))) || (keepModes && /^[rwxabt+U]{1,4}$/.test(body));
|
|
101
|
+
out += quote + (keep ? body : '') + quote;
|
|
102
|
+
index = end + quote.length;
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
out += char;
|
|
106
|
+
index += 1;
|
|
107
|
+
}
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The index of the parenthesis that closes the call whose opening one is at `open`. */
|
|
112
|
+
function callEnd(text, open) {
|
|
113
|
+
let depth = 0;
|
|
114
|
+
let quote;
|
|
115
|
+
for (let index = open; index < text.length; index += 1) {
|
|
116
|
+
const char = text[index];
|
|
117
|
+
if (quote !== undefined) {
|
|
118
|
+
if (char === '\\') index += 1;
|
|
119
|
+
else if (char === quote) quote = undefined;
|
|
120
|
+
} else if (char === '"' || char === "'") quote = char;
|
|
121
|
+
else if (char === '(') depth += 1;
|
|
122
|
+
else if (char === ')' && (depth -= 1) === 0) return index;
|
|
123
|
+
}
|
|
124
|
+
return text.length;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The top-level, comma-separated arguments of the call whose opening parenthesis is at `open`. */
|
|
128
|
+
function callArguments(text, open) {
|
|
129
|
+
const end = callEnd(text, open);
|
|
130
|
+
const args = [];
|
|
131
|
+
let depth = 0;
|
|
132
|
+
let quote;
|
|
133
|
+
let current = '';
|
|
134
|
+
for (let index = open + 1; index < end; index += 1) {
|
|
135
|
+
const char = text[index];
|
|
136
|
+
if (quote !== undefined) {
|
|
137
|
+
current += char;
|
|
138
|
+
if (char === '\\') {
|
|
139
|
+
current += text[index + 1] === undefined ? '' : text[index + 1];
|
|
140
|
+
index += 1;
|
|
141
|
+
} else if (char === quote) quote = undefined;
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
if (char === '"' || char === "'") quote = char;
|
|
145
|
+
if (char === '(' || char === '[' || char === '{') depth += 1;
|
|
146
|
+
if (char === ')' || char === ']' || char === '}') depth -= 1;
|
|
147
|
+
if (char === ',' && depth === 0) {
|
|
148
|
+
args.push(current.trim());
|
|
149
|
+
current = '';
|
|
150
|
+
} else current += char;
|
|
151
|
+
}
|
|
152
|
+
if (current.trim() !== '') args.push(current.trim());
|
|
153
|
+
return args;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** A string literal's text, or undefined when the argument is anything else. */
|
|
157
|
+
function literal(arg) {
|
|
158
|
+
const found = /^[a-zA-Z]{0,2}(['"])([\s\S]*)\1$/.exec(arg === undefined ? '' : arg);
|
|
159
|
+
return found === null ? undefined : found[2];
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Whether the text opens a file for writing: a mode that creates, truncates, appends or
|
|
164
|
+
* updates, or a mode this reader cannot see. Nested calls in the path (`open(Path('a'), 'w')`)
|
|
165
|
+
* and `mode=` are read as arguments, not as a pattern.
|
|
166
|
+
*/
|
|
167
|
+
function pythonOpensForWrite(text) {
|
|
168
|
+
for (const found of text.matchAll(/(\.?)\bopen\s*\(/g)) {
|
|
169
|
+
const args = callArguments(text, found.index + found[0].length - 1);
|
|
170
|
+
if (found[1] === '.') {
|
|
171
|
+
// A method such as `Path.open('w')` or `Path.open(mode='w')`: a mode-shaped first
|
|
172
|
+
// argument, or `mode=`, is the mode.
|
|
173
|
+
const keyword = args.find((arg) => /^mode\s*=/.test(arg));
|
|
174
|
+
const mode = literal(keyword === undefined ? args[0] : keyword.replace(/^mode\s*=\s*/, ''));
|
|
175
|
+
if (mode !== undefined && /^[rwxabt+U]+$/.test(mode) && /[wax+]/.test(mode)) return true;
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
const keyword = args.find((arg) => /^mode\s*=/.test(arg));
|
|
179
|
+
const modeArg = keyword === undefined ? args[1] : keyword.replace(/^mode\s*=\s*/, '');
|
|
180
|
+
if (modeArg === undefined) continue;
|
|
181
|
+
const mode = literal(modeArg);
|
|
182
|
+
if (mode === undefined || /[wax+]/.test(mode)) return true;
|
|
183
|
+
}
|
|
184
|
+
return false;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** The same for `fs.openSync(path, flags)`: a flag that writes, or one this reader cannot see. */
|
|
188
|
+
function nodeOpensForWrite(text) {
|
|
189
|
+
for (const found of text.matchAll(/\bopen(?:Sync)?\s*\(/g)) {
|
|
190
|
+
const flags = callArguments(text, found.index + found[0].length - 1)[1];
|
|
191
|
+
if (flags === undefined) continue;
|
|
192
|
+
const mode = literal(flags);
|
|
193
|
+
if (mode === undefined || /[wa+]/.test(mode)) return true;
|
|
194
|
+
}
|
|
195
|
+
return false;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* The family the script text proves, or `undefined`.
|
|
200
|
+
* @param {'python'|'node'} language
|
|
201
|
+
* @param {string} source
|
|
202
|
+
*/
|
|
203
|
+
function readScript(language, source) {
|
|
204
|
+
if (typeof source !== 'string' || source.trim() === '') return undefined;
|
|
205
|
+
const text = source.replace(PRINTING, '');
|
|
206
|
+
if (language === 'python') return readPython(text);
|
|
207
|
+
if (language === 'node') return readNode(text);
|
|
208
|
+
return undefined;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function pythonImportsAreReadable(text) {
|
|
212
|
+
const pairs = [...text.matchAll(/(?:^|;)[ \t]*(?:import[ \t]+([^\n#;]+)|from[ \t]+(\S+)[ \t]+import[ \t]+([^\n#;]+))/gm)];
|
|
213
|
+
for (const found of pairs) {
|
|
214
|
+
const names = found[2] === undefined ? found[1].split(',').map((part) => part.trim().split(/\s+/)[0]) : [found[2]];
|
|
215
|
+
for (const name of names) {
|
|
216
|
+
const root = name === undefined ? '' : name.split('.')[0];
|
|
217
|
+
if (root === '' || !PYTHON_MODULES.has(root)) return false;
|
|
218
|
+
}
|
|
219
|
+
// Names pulled out of `os` may be the deleting ones, so only the reading ones pass.
|
|
220
|
+
if (found[2] === 'os') {
|
|
221
|
+
for (const name of found[3].split(',').map((part) => part.trim().split(/\s+/)[0])) {
|
|
222
|
+
if (!PYTHON_OS_READ_NAMES.has(name)) return false;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
return true;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function readPython(text) {
|
|
230
|
+
const code = codeOf('python', text);
|
|
231
|
+
// A deletion the code calls is proven whatever else the script does or imports.
|
|
232
|
+
if (PYTHON_DELETES.test(code)) return 'destructive';
|
|
233
|
+
if (PYTHON_UNREADABLE.test(text)) return undefined;
|
|
234
|
+
if (!pythonImportsAreReadable(text)) return undefined;
|
|
235
|
+
if (PYTHON_WRITES.test(code) || pythonOpensForWrite(codeOf('python', text, true))) return 'preparing';
|
|
236
|
+
return 'exploring';
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function readNode(text) {
|
|
240
|
+
const code = codeOf('node', text);
|
|
241
|
+
if (NODE_DELETES.test(code)) return 'destructive';
|
|
242
|
+
if (NODE_UNREADABLE.test(text)) return undefined;
|
|
243
|
+
// Every module the script loads, by `require`, a static `import` or a dynamic one: a
|
|
244
|
+
// builtin from the list, or a JSON file. Anything else — a path, a package, an
|
|
245
|
+
// expression — is code this reader has not seen.
|
|
246
|
+
const specifiers = [];
|
|
247
|
+
for (const found of text.matchAll(/\b(?:require|import)\s*\(\s*(['"])([^'"]*)\1\s*\)/g)) specifiers.push(found[2]);
|
|
248
|
+
for (const found of text.matchAll(/\bimport\s+(?:[\w*${},\s]+\s+from\s+)?(['"])([^'"]+)\1/g)) specifiers.push(found[2]);
|
|
249
|
+
const calls = [...text.matchAll(/\b(?:require|import)\s*\(/g)].length;
|
|
250
|
+
const literals = [...text.matchAll(/\b(?:require|import)\s*\(\s*(['"])[^'"]*\1\s*\)/g)].length;
|
|
251
|
+
if (calls !== literals) return undefined;
|
|
252
|
+
for (const specifier of specifiers) {
|
|
253
|
+
const name = specifier.startsWith('node:') ? specifier.slice(5) : specifier;
|
|
254
|
+
if (/\.json$/.test(name) && !name.startsWith('http')) continue;
|
|
255
|
+
if (!NODE_MODULES.has(name)) return undefined;
|
|
256
|
+
}
|
|
257
|
+
// Names destructured out of the filesystem module may be the deleting or writing ones.
|
|
258
|
+
const destructured = /(?:\{([^}]*)\}\s*=\s*require\s*\(\s*['"](?:node:)?fs(?:\/promises)?['"]\s*\)|import\s*\{([^}]*)\}\s*from\s*['"](?:node:)?fs(?:\/promises)?['"])/g;
|
|
259
|
+
for (const found of text.matchAll(destructured)) {
|
|
260
|
+
for (const part of (found[1] === undefined ? found[2] : found[1]).split(',')) {
|
|
261
|
+
const name = part.trim().split(/\s*:\s*|\s+as\s+/)[0];
|
|
262
|
+
if (name !== '' && !NODE_FS_READ_NAMES.has(name)) return undefined;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
if (NODE_WRITES.test(code) || nodeOpensForWrite(codeOf('node', text, true))) return 'preparing';
|
|
266
|
+
return 'exploring';
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* The inline script a command's words hand an interpreter, or `undefined` when they hand it
|
|
271
|
+
* anything else (a file to run, a module, a flag this reader does not know).
|
|
272
|
+
* @param {string[]} words The words of ONE simple command, quotes folded.
|
|
273
|
+
* @param {string|undefined} body The text of the first heredoc the segment opens, if any.
|
|
274
|
+
*/
|
|
275
|
+
function inlineScript(words, body) {
|
|
276
|
+
// A node option that loads code before the script runs, wherever it stands.
|
|
277
|
+
if (words.some((word) => /^(-r|--require|--import|--loader|--experimental-loader|--env-file)(=|$)/.test(word))) return undefined;
|
|
278
|
+
const program = (words[0] === undefined ? '' : words[0]).split('/').pop();
|
|
279
|
+
const python = PYTHON_PROGRAM.test(program);
|
|
280
|
+
const node = NODE_PROGRAM.test(program) || program === 'node';
|
|
281
|
+
if (!python && !node) return undefined;
|
|
282
|
+
const plain = python ? PYTHON_PLAIN_FLAGS : NODE_PLAIN_FLAGS;
|
|
283
|
+
const payload = python ? new Set(['-c']) : new Set(['-e', '--eval', '-p', '--print']);
|
|
284
|
+
for (let index = 1; index < words.length; index += 1) {
|
|
285
|
+
const word = words[index] === undefined ? '' : words[index];
|
|
286
|
+
if (payload.has(word)) {
|
|
287
|
+
const script = words[index + 1];
|
|
288
|
+
return script === undefined ? undefined : { language: python ? 'python' : 'node', source: script };
|
|
289
|
+
}
|
|
290
|
+
if (word === '-') return body === undefined ? undefined : { language: python ? 'python' : 'node', source: body };
|
|
291
|
+
if (plain.has(word)) continue;
|
|
292
|
+
if (python && /^-[IBuESsOqbd]+$/.test(word)) continue;
|
|
293
|
+
// Anything else is a script path, a module, or a flag this reader cannot vouch for.
|
|
294
|
+
return undefined;
|
|
295
|
+
}
|
|
296
|
+
// No script argument: the interpreter reads its program from the heredoc on stdin.
|
|
297
|
+
return body === undefined ? undefined : { language: python ? 'python' : 'node', source: body };
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* The family an inline script names, or `undefined`.
|
|
302
|
+
* @param {string[]} words
|
|
303
|
+
* @param {string|undefined} body
|
|
304
|
+
*/
|
|
305
|
+
function inlineScriptActivity(words, body) {
|
|
306
|
+
try {
|
|
307
|
+
const script = inlineScript(words, body);
|
|
308
|
+
return script === undefined ? undefined : readScript(script.language, script.source);
|
|
309
|
+
} catch {
|
|
310
|
+
return undefined;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
module.exports = { inlineScriptActivity, readScript };
|
|
@@ -250,6 +250,10 @@ function registerFileCard(pi, deps = {}) {
|
|
|
250
250
|
}
|
|
251
251
|
|
|
252
252
|
module.exports = {
|
|
253
|
+
// The bridge's published object and this package's design id: the jobs card asks the same
|
|
254
|
+
// switch (`lib/jobs-card-resolver.js`) and must read it through the same gate.
|
|
255
|
+
ACTIVITY_DESIGN_ID,
|
|
256
|
+
bridgeApi,
|
|
253
257
|
createFileCardResolver,
|
|
254
258
|
registerFileCard,
|
|
255
259
|
};
|
package/lib/file-card.js
CHANGED
|
@@ -654,6 +654,14 @@ function fileResultSlot(tool, inherited, seams, shell) {
|
|
|
654
654
|
module.exports = {
|
|
655
655
|
FILE_TOOLS,
|
|
656
656
|
PREVIEW_ROWS,
|
|
657
|
+
// The drawing helpers the jobs card (`lib/jobs-card.js`) shares, so the two cards can never
|
|
658
|
+
// disagree about a tone, a hint, a theme fallback or how a result's text is read.
|
|
659
|
+
cardTone,
|
|
660
|
+
component,
|
|
661
|
+
expandHint,
|
|
662
|
+
optionFlag,
|
|
663
|
+
resultText,
|
|
664
|
+
themeFor,
|
|
657
665
|
fileCallRows,
|
|
658
666
|
fileCallSlot,
|
|
659
667
|
fileCardHeading,
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// The seam that makes `bash_background`, `monitor`, `job_stop` and `job_list` this package's
|
|
3
|
+
// jobs card (`lib/jobs-card.js`).
|
|
4
|
+
//
|
|
5
|
+
// Shaped like `lib/file-card-resolver.js`: the host resolves drawing through
|
|
6
|
+
// `pi.registerToolRenderer((toolName, next) => …)`, where `next()` is what the remaining
|
|
7
|
+
// resolvers and then the registered tool would draw. This module REGISTERS NOTHING, EXECUTES
|
|
8
|
+
// NOTHING and SHADOWS NOTHING: it chooses renderers for the four job tools and hands every
|
|
9
|
+
// other row back exactly as the chain resolved it.
|
|
10
|
+
//
|
|
11
|
+
// One difference from the file card, and it is deliberate. The file card forwards to the host's
|
|
12
|
+
// own renderers while its switch is off, so it can decide on every paint. These four tools have
|
|
13
|
+
// NO renderer of their own — Pi draws its plain default for them — so there is nothing to
|
|
14
|
+
// forward to. The switch is therefore read when the card is BUILT: any answer other than the
|
|
15
|
+
// activity design hands back exactly what the chain resolved, and Pi draws what it always drew.
|
|
16
|
+
// A switch flipped while a card is already on screen reaches the next job card, not that one.
|
|
17
|
+
//
|
|
18
|
+
// THE SWITCH is the bridge's `Card tags` line, read through its published reader, never a
|
|
19
|
+
// store path. It is strict: only the answer `design` carrying this package's activity design
|
|
20
|
+
// paints. No bridge, a bridge older than the reader, a reader that throws, `native`,
|
|
21
|
+
// `not-covered`, `missing`, another plugin's design and an answer nothing can read all leave
|
|
22
|
+
// Pi's drawing untouched, because here an unavailable answer must never change a row.
|
|
23
|
+
|
|
24
|
+
const { inheritedRenderers } = require('./file-card.js');
|
|
25
|
+
const { ACTIVITY_DESIGN_ID, bridgeApi } = require('./file-card-resolver.js');
|
|
26
|
+
const { CARD_CONTENT, cardContentLevel } = require('./card-content.js');
|
|
27
|
+
const { JOB_TOOLS, jobCallSlot, jobResultSlot } = require('./jobs-card.js');
|
|
28
|
+
|
|
29
|
+
const METRICS_FUNCTIONS = ['visibleWidth', 'truncateToWidth', 'wrapTextWithAnsi'];
|
|
30
|
+
|
|
31
|
+
const asObject = (value) => (value !== null && typeof value === 'object' ? value : {});
|
|
32
|
+
const hasFunction = (value, name) => value !== null && typeof value === 'object' && typeof value[name] === 'function';
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Whether the activity design draws `tool` right now. Strict: anything but this package's own
|
|
36
|
+
* design as the line's answer is a no. The reader never throws on the bridge's side and this
|
|
37
|
+
* one does not either.
|
|
38
|
+
*/
|
|
39
|
+
function jobsActivitySelected(tool) {
|
|
40
|
+
try {
|
|
41
|
+
const api = bridgeApi();
|
|
42
|
+
if (api === undefined || typeof api.resolveToolDesignSelection !== 'function') return false;
|
|
43
|
+
const answer = asObject(api.resolveToolDesignSelection(tool));
|
|
44
|
+
return answer.kind === 'design' && asObject(answer.design).id === ACTIVITY_DESIGN_ID;
|
|
45
|
+
} catch {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function assertMetrics(value) {
|
|
51
|
+
for (const name of METRICS_FUNCTIONS) {
|
|
52
|
+
if (!hasFunction(value, name)) throw new TypeError(`createJobsCardResolver requires metrics.${name} to be a function`);
|
|
53
|
+
}
|
|
54
|
+
return value;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The measurement seam, validated once: the object itself, or a function asked on every paint. */
|
|
58
|
+
function metricsSeam(value) {
|
|
59
|
+
if (typeof value === 'function') return value;
|
|
60
|
+
assertMetrics(value);
|
|
61
|
+
return () => value;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const usableMetrics = (value) => (METRICS_FUNCTIONS.every((name) => hasFunction(value, name)) ? value : undefined);
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* `createJobsCardResolver({ metrics, registerToolRenderer, theme })` — every host seam is an
|
|
68
|
+
* option, exactly as for the file card. Returns `{ registered, resolver }`; `resolver` is the
|
|
69
|
+
* function the host hook receives. An absent or throwing hook is no hook: nothing of ours is
|
|
70
|
+
* drawn, which is what an older host needs.
|
|
71
|
+
*/
|
|
72
|
+
function createJobsCardResolver(options) {
|
|
73
|
+
const opts = asObject(options);
|
|
74
|
+
const metrics = metricsSeam(opts.metrics);
|
|
75
|
+
const seams = {
|
|
76
|
+
theme: opts.theme,
|
|
77
|
+
metrics() {
|
|
78
|
+
try {
|
|
79
|
+
return usableMetrics(metrics());
|
|
80
|
+
} catch {
|
|
81
|
+
return undefined;
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
/** The conversation's content level, read now: `minimal` or the safe `default`. */
|
|
85
|
+
content() {
|
|
86
|
+
try {
|
|
87
|
+
return cardContentLevel() === CARD_CONTENT.MINIMAL ? CARD_CONTENT.MINIMAL : CARD_CONTENT.DEFAULT;
|
|
88
|
+
} catch {
|
|
89
|
+
return CARD_CONTENT.DEFAULT;
|
|
90
|
+
}
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
const resolver = (toolName, next) => {
|
|
94
|
+
const inherited = inheritedRenderers(next);
|
|
95
|
+
// Every tool this card does not own goes back untouched, byte for byte.
|
|
96
|
+
if (!JOB_TOOLS.includes(toolName)) return inherited;
|
|
97
|
+
// Pi's own drawing stays unless the line says activity, and unless a card can be measured.
|
|
98
|
+
if (!jobsActivitySelected(toolName)) return inherited;
|
|
99
|
+
if (seams.metrics() === undefined) return inherited;
|
|
100
|
+
return {
|
|
101
|
+
// This card frames itself, so the host must not box it too.
|
|
102
|
+
renderShell: 'self',
|
|
103
|
+
renderCall: jobCallSlot(toolName, seams),
|
|
104
|
+
renderResult: jobResultSlot(toolName, seams),
|
|
105
|
+
};
|
|
106
|
+
};
|
|
107
|
+
const register = opts.registerToolRenderer;
|
|
108
|
+
if (typeof register !== 'function') return { registered: false, resolver };
|
|
109
|
+
try {
|
|
110
|
+
register(resolver);
|
|
111
|
+
return { registered: true, resolver };
|
|
112
|
+
} catch {
|
|
113
|
+
return { registered: false, resolver };
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* The extension's one-line wiring point: register through the host's hook when it has one and
|
|
119
|
+
* report the outcome rather than throwing. A host without `registerToolRenderer` draws its own
|
|
120
|
+
* rows and loses nothing.
|
|
121
|
+
*/
|
|
122
|
+
function registerJobsCard(pi, deps = {}) {
|
|
123
|
+
if (typeof pi?.registerToolRenderer !== 'function') return { registered: false, resolver: undefined };
|
|
124
|
+
try {
|
|
125
|
+
return createJobsCardResolver({
|
|
126
|
+
metrics: deps.metrics,
|
|
127
|
+
theme: deps.theme,
|
|
128
|
+
registerToolRenderer: (resolver) => pi.registerToolRenderer(resolver),
|
|
129
|
+
});
|
|
130
|
+
} catch {
|
|
131
|
+
return { registered: false, resolver: undefined };
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
module.exports = {
|
|
136
|
+
createJobsCardResolver,
|
|
137
|
+
jobsActivitySelected,
|
|
138
|
+
registerJobsCard,
|
|
139
|
+
};
|