@termwire/cli 0.4.1 → 0.6.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/CHANGELOG.md +166 -0
- package/README.md +145 -8
- package/dist/agents.d.ts +24 -0
- package/dist/agents.js +54 -0
- package/dist/bin/termwire.js +2 -2
- package/dist/config-loader.d.ts +9 -0
- package/dist/config-loader.js +6 -3
- package/dist/config-writer.d.ts +17 -0
- package/dist/config-writer.js +46 -0
- package/dist/down.d.ts +40 -0
- package/dist/down.js +99 -0
- package/dist/exec.d.ts +10 -2
- package/dist/exec.js +7 -4
- package/dist/index.d.ts +7 -17
- package/dist/index.js +2 -9
- package/dist/install-prompt.d.ts +10 -0
- package/dist/install-prompt.js +100 -0
- package/dist/install.d.ts +92 -0
- package/dist/install.js +363 -0
- package/dist/layout-preview.d.ts +20 -0
- package/dist/layout-preview.js +38 -0
- package/dist/process-scan-darwin.d.ts +24 -0
- package/dist/process-scan-darwin.js +102 -0
- package/dist/process-scan-linux.d.ts +13 -0
- package/dist/process-scan-linux.js +66 -0
- package/dist/process-scan.d.ts +37 -23
- package/dist/process-scan.js +30 -131
- package/dist/program.d.ts +21 -50
- package/dist/program.js +199 -144
- package/dist/runtime.d.ts +84 -0
- package/dist/runtime.js +131 -0
- package/dist/skill.d.ts +13 -0
- package/dist/skill.js +17 -0
- package/dist/templates.d.ts +13 -0
- package/dist/templates.js +168 -0
- package/dist/workspaces.d.ts +45 -0
- package/dist/workspaces.js +116 -0
- package/dist/worktree.d.ts +15 -0
- package/dist/worktree.js +65 -7
- package/package.json +6 -3
- package/skills/termwire-open/SKILL.md +27 -0
package/dist/install.js
ADDED
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { agentDefinitions, findAgentDefinition, skillName, } from "./agents.js";
|
|
3
|
+
import { skillMarker } from "./skill.js";
|
|
4
|
+
import { findLayoutTemplate, layoutTemplates } from "./templates.js";
|
|
5
|
+
export const noLayout = "none";
|
|
6
|
+
export async function install(request, dependencies) {
|
|
7
|
+
const interactive = isInteractive(request, dependencies);
|
|
8
|
+
// A confirmation is only worth asking for what the user has not already said.
|
|
9
|
+
const asked = { any: false };
|
|
10
|
+
if (!interactive && !hasExplicitRequest(request)) {
|
|
11
|
+
throw new Error("install has nothing to do and no terminal to ask: pass --yes, --layout or --agents");
|
|
12
|
+
}
|
|
13
|
+
const configPath = await resolveConfigPath(request, dependencies);
|
|
14
|
+
const exists = await dependencies.pathExists(configPath);
|
|
15
|
+
const cancelled = {
|
|
16
|
+
cancelled: true,
|
|
17
|
+
configWritten: false,
|
|
18
|
+
agents: [],
|
|
19
|
+
failures: [],
|
|
20
|
+
};
|
|
21
|
+
const chosen = await resolveLayout(request, dependencies, interactive, configPath, exists, asked);
|
|
22
|
+
if (chosen === undefined)
|
|
23
|
+
return cancelled;
|
|
24
|
+
const decision = await decideExistingConfig({ chosen, exists, request, interactive, configPath, asked }, dependencies);
|
|
25
|
+
if (decision === undefined)
|
|
26
|
+
return cancelled;
|
|
27
|
+
const { layout, force } = decision;
|
|
28
|
+
const candidates = await agentCandidates(dependencies);
|
|
29
|
+
const selected = await resolveAgents(request, dependencies, interactive, candidates, asked);
|
|
30
|
+
if (selected === undefined)
|
|
31
|
+
return cancelled;
|
|
32
|
+
const skill = selected.length === 0 ? { contents: "" } : await readSkill(dependencies);
|
|
33
|
+
const agents = await planAgents({ selected, candidates, force: request.force === true, interactive, skill, asked }, dependencies);
|
|
34
|
+
if (agents === undefined)
|
|
35
|
+
return cancelled;
|
|
36
|
+
if (interactive && dependencies.prompt && asked.any) {
|
|
37
|
+
const summary = planSummary({ configPath, layout, exists, force, agents });
|
|
38
|
+
const accepted = await dependencies.prompt.confirm({ summary });
|
|
39
|
+
if (accepted === undefined || !accepted)
|
|
40
|
+
return cancelled;
|
|
41
|
+
}
|
|
42
|
+
return await apply({ configPath, layout, force, agents, skill }, dependencies);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* A config that is already there is only replaced when the user said so: `--force`, or a
|
|
46
|
+
* yes to the prompt. A default layout nobody asked for keeps it instead of turning a run
|
|
47
|
+
* that was really about agent registration into an error.
|
|
48
|
+
*/
|
|
49
|
+
async function decideExistingConfig(options, dependencies) {
|
|
50
|
+
const force = options.request.force === true;
|
|
51
|
+
if (options.chosen === noLayout || !options.exists || force) {
|
|
52
|
+
return { layout: options.chosen, force };
|
|
53
|
+
}
|
|
54
|
+
if (options.interactive && dependencies.prompt) {
|
|
55
|
+
options.asked.any = true;
|
|
56
|
+
const replace = await dependencies.prompt.replace({ path: options.configPath });
|
|
57
|
+
if (replace === undefined)
|
|
58
|
+
return undefined;
|
|
59
|
+
return replace ? { layout: options.chosen, force: true } : { layout: noLayout, force };
|
|
60
|
+
}
|
|
61
|
+
// A layout asked for by name conflicts with an existing file and is worth reporting;
|
|
62
|
+
// a layout that merely defaulted is not.
|
|
63
|
+
if (options.request.layout !== undefined)
|
|
64
|
+
return { layout: options.chosen, force };
|
|
65
|
+
dependencies.write(`Keeping ${options.configPath}; pass --layout <name> --force to replace it\n`);
|
|
66
|
+
return { layout: noLayout, force };
|
|
67
|
+
}
|
|
68
|
+
function isInteractive(request, dependencies) {
|
|
69
|
+
if (request.yes === true || dependencies.prompt === undefined)
|
|
70
|
+
return false;
|
|
71
|
+
return dependencies.isTerminal;
|
|
72
|
+
}
|
|
73
|
+
function hasExplicitRequest(request) {
|
|
74
|
+
return request.yes === true || request.layout !== undefined || request.agents !== undefined;
|
|
75
|
+
}
|
|
76
|
+
async function resolveConfigPath(request, dependencies) {
|
|
77
|
+
if (request.project !== true)
|
|
78
|
+
return dependencies.globalConfigPath();
|
|
79
|
+
const gitRoot = await dependencies.findGitRoot(dependencies.cwd());
|
|
80
|
+
if (gitRoot === undefined) {
|
|
81
|
+
throw new Error("--project requires a Git repository");
|
|
82
|
+
}
|
|
83
|
+
return join(gitRoot, ".termwire.jsonc");
|
|
84
|
+
}
|
|
85
|
+
async function resolveLayout(request, dependencies, interactive, path, exists, asked) {
|
|
86
|
+
if (request.layout !== undefined) {
|
|
87
|
+
if (request.layout === noLayout)
|
|
88
|
+
return noLayout;
|
|
89
|
+
const template = findLayoutTemplate(request.layout);
|
|
90
|
+
if (template === undefined) {
|
|
91
|
+
const known = [...layoutTemplates().map((entry) => entry.id), noLayout].join(", ");
|
|
92
|
+
throw new Error(`unknown layout: ${request.layout} (expected ${known})`);
|
|
93
|
+
}
|
|
94
|
+
return template.id;
|
|
95
|
+
}
|
|
96
|
+
// Asked for agents and nothing else: do not create a config nobody mentioned.
|
|
97
|
+
if (!interactive || dependencies.prompt === undefined) {
|
|
98
|
+
return request.agents === undefined ? "default" : noLayout;
|
|
99
|
+
}
|
|
100
|
+
asked.any = true;
|
|
101
|
+
return await dependencies.prompt.layout({ templates: layoutTemplates(), path, exists });
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* An agent counts as here when its own directory is: that is what proves it has been set
|
|
105
|
+
* up on this machine, and unlike a name on `PATH` it does not depend on a version
|
|
106
|
+
* manager's shim being healthy.
|
|
107
|
+
*/
|
|
108
|
+
async function agentCandidates(dependencies) {
|
|
109
|
+
return await Promise.all(agentDefinitions().map((agent) => agentCandidate(agent, dependencies)));
|
|
110
|
+
}
|
|
111
|
+
async function agentCandidate(agent, dependencies) {
|
|
112
|
+
if (!(await dependencies.pathExists(agent.home(dependencies.agentPaths)))) {
|
|
113
|
+
return { id: agent.id, title: agent.title, state: "missing" };
|
|
114
|
+
}
|
|
115
|
+
if (agent.skillPath === undefined) {
|
|
116
|
+
return { id: agent.id, title: agent.title, state: "manual" };
|
|
117
|
+
}
|
|
118
|
+
return {
|
|
119
|
+
id: agent.id,
|
|
120
|
+
title: agent.title,
|
|
121
|
+
state: "ready",
|
|
122
|
+
path: agent.skillPath(dependencies.agentPaths),
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
async function resolveAgents(request, dependencies, interactive, candidates, asked) {
|
|
126
|
+
if (request.agents !== undefined)
|
|
127
|
+
return request.agents;
|
|
128
|
+
if (!interactive || dependencies.prompt === undefined)
|
|
129
|
+
return [];
|
|
130
|
+
asked.any = true;
|
|
131
|
+
return await dependencies.prompt.agents({ candidates });
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Decides what happens to each selected agent, asking whatever needs asking. Doing it
|
|
135
|
+
* here rather than while writing keeps one promise: after the plan is confirmed, nothing
|
|
136
|
+
* else interrupts, and the summary says everything that is about to happen.
|
|
137
|
+
*/
|
|
138
|
+
async function planAgents(options, dependencies) {
|
|
139
|
+
if (options.selected.length === 0)
|
|
140
|
+
return [];
|
|
141
|
+
const { skill } = options;
|
|
142
|
+
const plans = [];
|
|
143
|
+
for (const id of options.selected) {
|
|
144
|
+
const agent = findAgentDefinition(id);
|
|
145
|
+
const candidate = options.candidates.find((entry) => entry.id === id);
|
|
146
|
+
if (agent === undefined || candidate === undefined)
|
|
147
|
+
continue;
|
|
148
|
+
if (candidate.state === "missing") {
|
|
149
|
+
plans.push({ id, title: agent.title, action: "unavailable" });
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
if (candidate.state !== "ready" || candidate.path === undefined) {
|
|
153
|
+
plans.push({ id, title: agent.title, action: "manual" });
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
if ("error" in skill) {
|
|
157
|
+
plans.push({
|
|
158
|
+
id,
|
|
159
|
+
title: agent.title,
|
|
160
|
+
action: "install",
|
|
161
|
+
path: candidate.path,
|
|
162
|
+
error: skill.error,
|
|
163
|
+
});
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
const existing = await readExistingSkill(candidate.path, dependencies);
|
|
167
|
+
if ("error" in existing) {
|
|
168
|
+
plans.push({
|
|
169
|
+
id,
|
|
170
|
+
title: agent.title,
|
|
171
|
+
action: "install",
|
|
172
|
+
path: candidate.path,
|
|
173
|
+
error: existing.error,
|
|
174
|
+
});
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
if (existing.contents === skill.contents) {
|
|
178
|
+
plans.push({ id, title: agent.title, action: "present", path: candidate.path });
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
if (existing.contents === undefined) {
|
|
182
|
+
plans.push({ id, title: agent.title, action: "install", path: candidate.path });
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
if (options.force || existing.contents.includes(skillMarker)) {
|
|
186
|
+
plans.push({ id, title: agent.title, action: "replace", path: candidate.path });
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
// Theirs, not ours: the marker is gone, so ask rather than overwrite in passing.
|
|
190
|
+
if (!options.interactive || dependencies.prompt === undefined) {
|
|
191
|
+
plans.push({ id, title: agent.title, action: "keep", path: candidate.path });
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
options.asked.any = true;
|
|
195
|
+
const replace = await dependencies.prompt.replace({ path: candidate.path });
|
|
196
|
+
if (replace === undefined)
|
|
197
|
+
return undefined;
|
|
198
|
+
plans.push({
|
|
199
|
+
id,
|
|
200
|
+
title: agent.title,
|
|
201
|
+
action: replace ? "replace" : "keep",
|
|
202
|
+
path: candidate.path,
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
return plans;
|
|
206
|
+
}
|
|
207
|
+
function planSummary(plan) {
|
|
208
|
+
const lines = [];
|
|
209
|
+
if (plan.layout === noLayout) {
|
|
210
|
+
lines.push("Layout: leave the configuration alone");
|
|
211
|
+
}
|
|
212
|
+
else {
|
|
213
|
+
const replacing = plan.exists ? (plan.force ? "replace" : "keep, already exists") : "write";
|
|
214
|
+
lines.push(`Layout: ${plan.layout} — ${replacing} ${plan.configPath}`);
|
|
215
|
+
}
|
|
216
|
+
if (plan.agents.length === 0) {
|
|
217
|
+
lines.push("Agents: none");
|
|
218
|
+
return lines;
|
|
219
|
+
}
|
|
220
|
+
for (const agent of plan.agents) {
|
|
221
|
+
lines.push(`${agent.title}: ${summariseAction(agent)}`);
|
|
222
|
+
}
|
|
223
|
+
return lines;
|
|
224
|
+
}
|
|
225
|
+
function summariseAction(agent) {
|
|
226
|
+
if (agent.error !== undefined)
|
|
227
|
+
return `cannot install: ${agent.error}`;
|
|
228
|
+
if (agent.action === "manual")
|
|
229
|
+
return "no skills, print the line to add";
|
|
230
|
+
if (agent.action === "unavailable")
|
|
231
|
+
return "not set up here, skip";
|
|
232
|
+
if (agent.action === "present")
|
|
233
|
+
return `already current at ${agent.path}`;
|
|
234
|
+
if (agent.action === "keep")
|
|
235
|
+
return `keep your ${agent.path}`;
|
|
236
|
+
if (agent.action === "replace")
|
|
237
|
+
return `replace ${agent.path}`;
|
|
238
|
+
return `write ${agent.path}`;
|
|
239
|
+
}
|
|
240
|
+
async function apply(plan, dependencies) {
|
|
241
|
+
const result = {
|
|
242
|
+
cancelled: false,
|
|
243
|
+
configPath: plan.configPath,
|
|
244
|
+
configWritten: false,
|
|
245
|
+
agents: [],
|
|
246
|
+
failures: [],
|
|
247
|
+
};
|
|
248
|
+
if (plan.layout !== noLayout) {
|
|
249
|
+
const template = findLayoutTemplate(plan.layout);
|
|
250
|
+
if (template === undefined)
|
|
251
|
+
throw new Error(`unknown layout: ${plan.layout}`);
|
|
252
|
+
try {
|
|
253
|
+
await dependencies.writeConfig({
|
|
254
|
+
path: plan.configPath,
|
|
255
|
+
contents: template.contents,
|
|
256
|
+
force: plan.force,
|
|
257
|
+
});
|
|
258
|
+
result.configWritten = true;
|
|
259
|
+
dependencies.write(`Wrote ${plan.configPath} (${template.id})\n`);
|
|
260
|
+
}
|
|
261
|
+
catch (error) {
|
|
262
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
263
|
+
result.failures.push(message);
|
|
264
|
+
dependencies.write(`Config not written: ${message}\n`);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
for (const agent of plan.agents) {
|
|
268
|
+
result.agents.push(await runAgentPlan(agent, plan.skill, dependencies));
|
|
269
|
+
}
|
|
270
|
+
for (const outcome of result.agents) {
|
|
271
|
+
if (outcome.outcome === "failed" && outcome.detail !== undefined) {
|
|
272
|
+
result.failures.push(outcome.detail);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
writeNextSteps(result, dependencies);
|
|
276
|
+
return result;
|
|
277
|
+
}
|
|
278
|
+
async function readSkill(dependencies) {
|
|
279
|
+
try {
|
|
280
|
+
return { contents: await dependencies.readFile(dependencies.skillSource) };
|
|
281
|
+
}
|
|
282
|
+
catch (error) {
|
|
283
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
284
|
+
return { error: `cannot read ${dependencies.skillSource}: ${reason}` };
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
async function runAgentPlan(plan, skill, dependencies) {
|
|
288
|
+
const agent = findAgentDefinition(plan.id);
|
|
289
|
+
if (plan.action === "unavailable") {
|
|
290
|
+
dependencies.write(`${plan.title} is not set up here, skipping\n`);
|
|
291
|
+
return { id: plan.id, outcome: "unavailable" };
|
|
292
|
+
}
|
|
293
|
+
if (plan.action === "manual") {
|
|
294
|
+
dependencies.write(`${plan.title} takes no skills:\n`);
|
|
295
|
+
if (agent !== undefined)
|
|
296
|
+
writeManual(agent, dependencies);
|
|
297
|
+
return { id: plan.id, outcome: "manual" };
|
|
298
|
+
}
|
|
299
|
+
if (plan.error !== undefined) {
|
|
300
|
+
const detail = `${plan.title}: ${plan.error}`;
|
|
301
|
+
dependencies.write(`${detail}\n`);
|
|
302
|
+
return { id: plan.id, outcome: "failed", detail };
|
|
303
|
+
}
|
|
304
|
+
if (plan.action === "present") {
|
|
305
|
+
dependencies.write(`${plan.title} already has the ${skillName} skill\n`);
|
|
306
|
+
return { id: plan.id, outcome: "present" };
|
|
307
|
+
}
|
|
308
|
+
if (plan.action === "keep") {
|
|
309
|
+
dependencies.write(`${plan.title}: keeping your ${plan.path}; pass --force to replace it\n`);
|
|
310
|
+
return { id: plan.id, outcome: "kept" };
|
|
311
|
+
}
|
|
312
|
+
const path = plan.path;
|
|
313
|
+
if (path === undefined) {
|
|
314
|
+
const detail = `${plan.title}: no skill path`;
|
|
315
|
+
return { id: plan.id, outcome: "failed", detail };
|
|
316
|
+
}
|
|
317
|
+
if ("error" in skill) {
|
|
318
|
+
const detail = `${plan.title}: ${skill.error}`;
|
|
319
|
+
return { id: plan.id, outcome: "failed", detail };
|
|
320
|
+
}
|
|
321
|
+
try {
|
|
322
|
+
await dependencies.writeConfig({
|
|
323
|
+
path,
|
|
324
|
+
contents: skill.contents,
|
|
325
|
+
force: plan.action === "replace",
|
|
326
|
+
});
|
|
327
|
+
dependencies.write(`Wrote ${path}\n`);
|
|
328
|
+
return { id: plan.id, outcome: "installed" };
|
|
329
|
+
}
|
|
330
|
+
catch (error) {
|
|
331
|
+
const detail = `${plan.title}: ${error instanceof Error ? error.message : String(error)}`;
|
|
332
|
+
dependencies.write(`${detail}\n`);
|
|
333
|
+
return { id: plan.id, outcome: "failed", detail };
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* The file that is there now, `undefined` contents when there is none. An unreadable file
|
|
338
|
+
* is an error rather than "different": treating it as different would report it as the
|
|
339
|
+
* user's own version and quietly keep whatever is broken there.
|
|
340
|
+
*/
|
|
341
|
+
async function readExistingSkill(path, dependencies) {
|
|
342
|
+
if (!(await dependencies.pathExists(path)))
|
|
343
|
+
return { contents: undefined };
|
|
344
|
+
try {
|
|
345
|
+
return { contents: await dependencies.readFile(path) };
|
|
346
|
+
}
|
|
347
|
+
catch (error) {
|
|
348
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
349
|
+
return { error: `cannot read ${path}: ${reason}` };
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
function writeManual(agent, dependencies) {
|
|
353
|
+
for (const line of agent.manual) {
|
|
354
|
+
dependencies.write(line.length === 0 ? "\n" : ` ${line}\n`);
|
|
355
|
+
}
|
|
356
|
+
dependencies.write("\n");
|
|
357
|
+
}
|
|
358
|
+
function writeNextSteps(result, dependencies) {
|
|
359
|
+
if (!result.agents.some((agent) => agent.outcome === "installed"))
|
|
360
|
+
return;
|
|
361
|
+
dependencies.write("The skill runs `termwire open`, so it works in a shell created by `termwire up`. " +
|
|
362
|
+
"Allow it once with `Bash(termwire open:*)` to skip the approval prompt.\n");
|
|
363
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export interface PreviewChoice {
|
|
2
|
+
label: string;
|
|
3
|
+
hint?: string;
|
|
4
|
+
preview: readonly string[];
|
|
5
|
+
}
|
|
6
|
+
export interface RenderChoicesOptions {
|
|
7
|
+
choices: readonly PreviewChoice[];
|
|
8
|
+
/** Index of the highlighted choice, whose preview is the one drawn. */
|
|
9
|
+
cursor: number;
|
|
10
|
+
/** Terminal width; below what the two columns need, the preview goes underneath. */
|
|
11
|
+
columns: number;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Draws the choices with the highlighted one's window layout beside them, so moving
|
|
15
|
+
* through the list shows what each template would create. The hint goes underneath
|
|
16
|
+
* rather than after the label, because a sentence in the left column pushes the
|
|
17
|
+
* drawing off a normal terminal. Too narrow for two columns and the drawing stacks
|
|
18
|
+
* under the list instead of wrapping the boxes into nonsense.
|
|
19
|
+
*/
|
|
20
|
+
export declare function renderChoices({ choices, cursor, columns }: RenderChoicesOptions): string;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
const gutter = " ";
|
|
2
|
+
const activeMarker = "●";
|
|
3
|
+
const inactiveMarker = "○";
|
|
4
|
+
/**
|
|
5
|
+
* Draws the choices with the highlighted one's window layout beside them, so moving
|
|
6
|
+
* through the list shows what each template would create. The hint goes underneath
|
|
7
|
+
* rather than after the label, because a sentence in the left column pushes the
|
|
8
|
+
* drawing off a normal terminal. Too narrow for two columns and the drawing stacks
|
|
9
|
+
* under the list instead of wrapping the boxes into nonsense.
|
|
10
|
+
*/
|
|
11
|
+
export function renderChoices({ choices, cursor, columns }) {
|
|
12
|
+
const selected = Math.min(Math.max(cursor, 0), Math.max(choices.length - 1, 0));
|
|
13
|
+
const left = choices.map((choice, index) => `${index === selected ? activeMarker : inactiveMarker} ${choice.label}`);
|
|
14
|
+
const active = choices[selected];
|
|
15
|
+
const hint = active?.hint === undefined ? [] : [` ${active.hint}`];
|
|
16
|
+
const preview = active?.preview ?? [];
|
|
17
|
+
if (preview.length === 0)
|
|
18
|
+
return [...left, ...hint].join("\n");
|
|
19
|
+
const leftWidth = widestOf(left);
|
|
20
|
+
const previewWidth = widestOf(preview);
|
|
21
|
+
if (leftWidth + gutter.length + previewWidth > columns) {
|
|
22
|
+
return [...left, "", ...preview, ...hint].join("\n");
|
|
23
|
+
}
|
|
24
|
+
const height = Math.max(left.length, preview.length);
|
|
25
|
+
const rows = [];
|
|
26
|
+
for (let index = 0; index < height; index += 1) {
|
|
27
|
+
const text = left[index] ?? "";
|
|
28
|
+
const art = preview[index] ?? "";
|
|
29
|
+
rows.push(art.length === 0 ? text : `${pad(text, leftWidth)}${gutter}${art}`);
|
|
30
|
+
}
|
|
31
|
+
return [...rows, ...hint].join("\n");
|
|
32
|
+
}
|
|
33
|
+
function widestOf(lines) {
|
|
34
|
+
return lines.reduce((widest, line) => Math.max(widest, line.length), 0);
|
|
35
|
+
}
|
|
36
|
+
function pad(text, width) {
|
|
37
|
+
return text.length >= width ? text : text + " ".repeat(width - text.length);
|
|
38
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { Exec } from "./exec.js";
|
|
2
|
+
import { type ProcessEntry, type SessionScanner } from "./process-scan.js";
|
|
3
|
+
export interface DarwinScanDependencies {
|
|
4
|
+
exec: Exec;
|
|
5
|
+
uid: number;
|
|
6
|
+
}
|
|
7
|
+
export interface DarwinProcessRow extends ProcessEntry {
|
|
8
|
+
/** The command line, followed by the environment when `ps -E` could read it. */
|
|
9
|
+
details: string;
|
|
10
|
+
}
|
|
11
|
+
export declare function parseDarwinProcesses(stdout: string): DarwinProcessRow[];
|
|
12
|
+
export declare function parseDarwinArguments(stdout: string): Map<number, string>;
|
|
13
|
+
/**
|
|
14
|
+
* True when `text` assigns `needle`, meaning the match is a whole space-separated
|
|
15
|
+
* token. A command line that merely mentions the variable never qualifies.
|
|
16
|
+
*/
|
|
17
|
+
export declare function containsAssignment(text: string, needle: string): boolean;
|
|
18
|
+
/**
|
|
19
|
+
* macOS has no `/proc`, so the environment comes from `ps -E`, which appends it to
|
|
20
|
+
* the command column. A process that only mentions the label on its command line
|
|
21
|
+
* would look identical, so every candidate is re-read without `-E` and the command
|
|
22
|
+
* line is stripped off before the label is looked up in what remains.
|
|
23
|
+
*/
|
|
24
|
+
export declare function createDarwinScanner(dependencies: DarwinScanDependencies): SessionScanner;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { emptyLabels, sessionLabel, } from "./process-scan.js";
|
|
2
|
+
/**
|
|
3
|
+
* One row of `ps -o pid=,ppid=,rss=,command=`: three right-aligned numbers, then
|
|
4
|
+
* everything after the first space as a single field, because the command line and
|
|
5
|
+
* the environment `-E` appends to it are not separable here.
|
|
6
|
+
*/
|
|
7
|
+
const processRow = /^\s*(\d+)\s+(\d+)\s+(\d+)\s(.*)$/;
|
|
8
|
+
/** One row of `ps -o pid=,args=`: the pid, then the command line by itself. */
|
|
9
|
+
const argumentsRow = /^\s*(\d+)\s(.*)$/;
|
|
10
|
+
export function parseDarwinProcesses(stdout) {
|
|
11
|
+
const rows = [];
|
|
12
|
+
for (const line of stdout.split("\n")) {
|
|
13
|
+
const parsed = processRow.exec(line);
|
|
14
|
+
if (!parsed)
|
|
15
|
+
continue;
|
|
16
|
+
rows.push({
|
|
17
|
+
pid: Number(parsed[1]),
|
|
18
|
+
ppid: Number(parsed[2]),
|
|
19
|
+
rss: Number(parsed[3]),
|
|
20
|
+
details: parsed[4],
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
return rows;
|
|
24
|
+
}
|
|
25
|
+
export function parseDarwinArguments(stdout) {
|
|
26
|
+
const args = new Map();
|
|
27
|
+
for (const line of stdout.split("\n")) {
|
|
28
|
+
const parsed = argumentsRow.exec(line);
|
|
29
|
+
if (!parsed)
|
|
30
|
+
continue;
|
|
31
|
+
args.set(Number(parsed[1]), parsed[2]);
|
|
32
|
+
}
|
|
33
|
+
return args;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* True when `text` assigns `needle`, meaning the match is a whole space-separated
|
|
37
|
+
* token. A command line that merely mentions the variable never qualifies.
|
|
38
|
+
*/
|
|
39
|
+
export function containsAssignment(text, needle) {
|
|
40
|
+
let index = text.indexOf(needle);
|
|
41
|
+
while (index !== -1) {
|
|
42
|
+
const before = index === 0 ? " " : text.charAt(index - 1);
|
|
43
|
+
const after = index + needle.length >= text.length ? " " : text.charAt(index + needle.length);
|
|
44
|
+
if (/\s/.test(before) && /\s/.test(after))
|
|
45
|
+
return true;
|
|
46
|
+
index = text.indexOf(needle, index + 1);
|
|
47
|
+
}
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* macOS has no `/proc`, so the environment comes from `ps -E`, which appends it to
|
|
52
|
+
* the command column. A process that only mentions the label on its command line
|
|
53
|
+
* would look identical, so every candidate is re-read without `-E` and the command
|
|
54
|
+
* line is stripped off before the label is looked up in what remains.
|
|
55
|
+
*/
|
|
56
|
+
export function createDarwinScanner(dependencies) {
|
|
57
|
+
return async (sessions) => {
|
|
58
|
+
const needles = new Map(sessions.map((session) => [session, sessionLabel(session)]));
|
|
59
|
+
const rows = parseDarwinProcesses(await runPs(dependencies.exec, [
|
|
60
|
+
"ps",
|
|
61
|
+
"-Eww",
|
|
62
|
+
"-o",
|
|
63
|
+
"pid=,ppid=,rss=,command=",
|
|
64
|
+
"-U",
|
|
65
|
+
String(dependencies.uid),
|
|
66
|
+
]));
|
|
67
|
+
const processes = rows.map(({ pid, ppid, rss }) => ({ pid, ppid, rss }));
|
|
68
|
+
const labeled = emptyLabels(sessions);
|
|
69
|
+
// Hoisted: this runs once per process on the machine, times the sessions asked for.
|
|
70
|
+
const wanted = [...needles.values()];
|
|
71
|
+
const candidates = rows.filter((row) => wanted.some((needle) => containsAssignment(row.details, needle)));
|
|
72
|
+
if (candidates.length === 0) {
|
|
73
|
+
return { processes, labeled };
|
|
74
|
+
}
|
|
75
|
+
const args = parseDarwinArguments(await runPs(dependencies.exec, ["ps", "-ww", "-o", "pid=,args=", "-p", candidates.map((c) => c.pid).join(",")],
|
|
76
|
+
// `ps` exits non-zero when none of the requested pids exist any more, and a
|
|
77
|
+
// candidate that just died is simply not a target.
|
|
78
|
+
{ allowMissingPids: true }));
|
|
79
|
+
for (const row of candidates) {
|
|
80
|
+
const argv = args.get(row.pid);
|
|
81
|
+
if (argv === undefined || !row.details.startsWith(argv))
|
|
82
|
+
continue;
|
|
83
|
+
const environment = row.details.slice(argv.length);
|
|
84
|
+
for (const [session, needle] of needles) {
|
|
85
|
+
if (containsAssignment(environment, needle))
|
|
86
|
+
labeled.get(session)?.push(row.pid);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return { processes, labeled };
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
async function runPs(exec, argv, options = {}) {
|
|
93
|
+
const execution = await exec(argv);
|
|
94
|
+
if (execution.exitCode === 0)
|
|
95
|
+
return execution.stdout;
|
|
96
|
+
if (options.allowMissingPids && execution.stdout.trim().length === 0)
|
|
97
|
+
return "";
|
|
98
|
+
// A failed listing must not read as an empty one: that would log a clean reap
|
|
99
|
+
// while the processes it exists to kill keep running.
|
|
100
|
+
const details = execution.stderr.trim();
|
|
101
|
+
throw new Error(`${argv.join(" ")} failed (exit ${execution.exitCode})${details ? `: ${details}` : ""}`);
|
|
102
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type SessionScanner } from "./process-scan.js";
|
|
2
|
+
export interface LinuxScanDependencies {
|
|
3
|
+
readdir: (path: string) => Promise<string[]>;
|
|
4
|
+
readFile: (path: string) => Promise<string>;
|
|
5
|
+
}
|
|
6
|
+
/** The second field of `statm` is the resident set, in pages. */
|
|
7
|
+
export declare function parseLinuxRss(statm: string): number;
|
|
8
|
+
export declare function parseLinuxPpid(stat: string): number | undefined;
|
|
9
|
+
/**
|
|
10
|
+
* Linux reads the environment straight out of `/proc`, where it is NUL-separated, so
|
|
11
|
+
* a label is an exact element and no command line can be mistaken for one.
|
|
12
|
+
*/
|
|
13
|
+
export declare function createLinuxScanner(dependencies: LinuxScanDependencies): SessionScanner;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { emptyLabels, sessionLabel, } from "./process-scan.js";
|
|
2
|
+
/**
|
|
3
|
+
* `/proc/<pid>/statm` counts pages, and Node exposes no page size, so the common
|
|
4
|
+
* 4 KiB is assumed: a kernel with larger pages only understates the column.
|
|
5
|
+
*/
|
|
6
|
+
const pageKib = 4;
|
|
7
|
+
/** A `/proc` entry that is a process rather than `self` or `uptime`: digits only. */
|
|
8
|
+
const processDirectory = /^\d+$/;
|
|
9
|
+
/** The second field of `statm` is the resident set, in pages. */
|
|
10
|
+
export function parseLinuxRss(statm) {
|
|
11
|
+
const pages = Number(statm.trim().split(/\s+/)[1]);
|
|
12
|
+
return Number.isInteger(pages) ? pages * pageKib : 0;
|
|
13
|
+
}
|
|
14
|
+
export function parseLinuxPpid(stat) {
|
|
15
|
+
const commandEnd = stat.lastIndexOf(")");
|
|
16
|
+
if (commandEnd === -1)
|
|
17
|
+
return undefined;
|
|
18
|
+
const fields = stat
|
|
19
|
+
.slice(commandEnd + 1)
|
|
20
|
+
.trim()
|
|
21
|
+
.split(/\s+/);
|
|
22
|
+
const ppid = Number(fields[1]);
|
|
23
|
+
return Number.isInteger(ppid) ? ppid : undefined;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Linux reads the environment straight out of `/proc`, where it is NUL-separated, so
|
|
27
|
+
* a label is an exact element and no command line can be mistaken for one.
|
|
28
|
+
*/
|
|
29
|
+
export function createLinuxScanner(dependencies) {
|
|
30
|
+
return async (sessions) => {
|
|
31
|
+
const needles = new Map(sessions.map((session) => [session, sessionLabel(session)]));
|
|
32
|
+
const processes = [];
|
|
33
|
+
const labeled = emptyLabels(sessions);
|
|
34
|
+
for (const entry of await dependencies.readdir("/proc")) {
|
|
35
|
+
if (!processDirectory.test(entry))
|
|
36
|
+
continue;
|
|
37
|
+
const pid = Number(entry);
|
|
38
|
+
const stat = await readOptional(dependencies, `/proc/${entry}/stat`);
|
|
39
|
+
if (stat === undefined)
|
|
40
|
+
continue;
|
|
41
|
+
const ppid = parseLinuxPpid(stat);
|
|
42
|
+
if (ppid === undefined)
|
|
43
|
+
continue;
|
|
44
|
+
const statm = await readOptional(dependencies, `/proc/${entry}/statm`);
|
|
45
|
+
processes.push({ pid, ppid, rss: statm === undefined ? 0 : parseLinuxRss(statm) });
|
|
46
|
+
// Readable only for our own processes, so other users are skipped silently.
|
|
47
|
+
const environ = await readOptional(dependencies, `/proc/${entry}/environ`);
|
|
48
|
+
if (environ === undefined)
|
|
49
|
+
continue;
|
|
50
|
+
const assignments = new Set(environ.split("\0"));
|
|
51
|
+
for (const [session, needle] of needles) {
|
|
52
|
+
if (assignments.has(needle))
|
|
53
|
+
labeled.get(session)?.push(pid);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return { processes, labeled };
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
async function readOptional(dependencies, path) {
|
|
60
|
+
try {
|
|
61
|
+
return await dependencies.readFile(path);
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return undefined;
|
|
65
|
+
}
|
|
66
|
+
}
|