@impact-ai/setup 0.0.0-stage → 0.1.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.
@@ -0,0 +1,177 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ // Finding programs, running them with their output read line by line, stopping them, and opening the browser.
4
+
5
+ import { spawn, spawnSync } from "node:child_process";
6
+ import { accessSync, constants, statSync } from "node:fs";
7
+ import path from "node:path";
8
+
9
+ const WINDOWS = process.platform === "win32";
10
+
11
+ /**
12
+ * The full path of a program on the PATH, or null.
13
+ * @param {string} command
14
+ * @param {Record<string, string | undefined>} env
15
+ */
16
+ export function which(command, env) {
17
+ const directories = (env.PATH ?? env.Path ?? "").split(path.delimiter).filter(Boolean);
18
+ const extensions = WINDOWS ? (env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";").filter(Boolean) : [""];
19
+ for (const directory of directories) {
20
+ for (const extension of extensions) {
21
+ const candidate = path.join(directory, command + extension);
22
+ try {
23
+ if (!statSync(candidate).isFile()) continue;
24
+ if (!WINDOWS) accessSync(candidate, constants.X_OK);
25
+ return candidate;
26
+ } catch {
27
+ // not here
28
+ }
29
+ }
30
+ }
31
+ return null;
32
+ }
33
+
34
+ function quoteForCmd(arg) {
35
+ return `"${arg.replace(/"/g, '""')}"`;
36
+ }
37
+
38
+ /** The processes of a process group, from ps. */
39
+ function groupMembers(group) {
40
+ const listed = spawnSync("ps", ["-A", "-o", "pid=,pgid="], { encoding: "utf8" });
41
+ if (listed.status !== 0) return [];
42
+ return listed.stdout
43
+ .split("\n")
44
+ .map((line) => line.trim().split(/\s+/).map(Number))
45
+ .filter(([pid, pgid]) => pgid === group && pid > 0)
46
+ .map(([pid]) => pid);
47
+ }
48
+
49
+ /** Calls onLine for each line of a stream, the last one too when it has no line break. */
50
+ function eachLine(stream, onLine) {
51
+ let pending = "";
52
+ stream.setEncoding("utf8");
53
+ stream.on("data", (chunk) => {
54
+ pending += chunk;
55
+ let at = pending.indexOf("\n");
56
+ while (at !== -1) {
57
+ onLine(pending.slice(0, at).replace(/\r$/, ""));
58
+ pending = pending.slice(at + 1);
59
+ at = pending.indexOf("\n");
60
+ }
61
+ });
62
+ stream.on("end", () => {
63
+ if (pending) onLine(pending.replace(/\r$/, ""));
64
+ pending = "";
65
+ });
66
+ }
67
+
68
+ /**
69
+ * Start a program in a process group of its own (so that it can be stopped with everything it started), its stdin
70
+ * given `input` and closed, its output read line by line.
71
+ * @param {string} file the program, or with `shell` a command line
72
+ * @param {string[]} args
73
+ * @param {{ cwd: string, env: Record<string, string | undefined>, input?: string, shell?: boolean,
74
+ * onLine?: (line: string, stream: "stdout" | "stderr") => void, settleOn?: "close" | "exit" }} options
75
+ * settleOn: "close" waits for the output to end too (for a reply that is read whole), "exit" only for the process
76
+ * (for an application that may leave a child holding its output)
77
+ */
78
+ export function start(file, args, { cwd, env, input, shell = false, onLine = () => {}, settleOn = "close" }) {
79
+ let command = file;
80
+ let commandArgs = args;
81
+ let useShell = shell;
82
+ if (!shell && WINDOWS && /\.(?:cmd|bat)$/i.test(file)) {
83
+ // Node runs a .cmd or .bat file only through cmd.exe; the arguments here are the command's own flags.
84
+ command = [quoteForCmd(file), ...args.map(quoteForCmd)].join(" ");
85
+ commandArgs = [];
86
+ useShell = true;
87
+ }
88
+ const child = spawn(command, commandArgs, {
89
+ cwd,
90
+ env,
91
+ shell: useShell,
92
+ detached: !WINDOWS,
93
+ stdio: ["pipe", "pipe", "pipe"],
94
+ windowsHide: true,
95
+ });
96
+ let stdout = "";
97
+ const exited = new Promise((resolve) => {
98
+ let settled = false;
99
+ const settle = (result) => {
100
+ if (!settled) {
101
+ settled = true;
102
+ resolve(result);
103
+ }
104
+ };
105
+ child.on("error", (error) => settle({ code: null, signal: null, error: error.code || error.message, stdout }));
106
+ child.on(settleOn, (code, signal) => settle({ code, signal, error: null, stdout }));
107
+ });
108
+ eachLine(child.stdout, (line) => {
109
+ stdout += `${line}\n`;
110
+ onLine(line, "stdout");
111
+ });
112
+ eachLine(child.stderr, (line) => onLine(line, "stderr"));
113
+ child.stdin.on("error", () => {});
114
+ child.stdin.end(input ?? "");
115
+ return {
116
+ child,
117
+ exited,
118
+ // Stop the program and what it started in its group, even after the program itself ended (a shell that left
119
+ // the application running).
120
+ stop() {
121
+ if (child.pid === undefined) return;
122
+ if (WINDOWS) {
123
+ if (child.exitCode === null && child.signalCode === null) {
124
+ spawn("taskkill", ["/pid", String(child.pid), "/t", "/f"], { stdio: "ignore", windowsHide: true }).on("error", () => {});
125
+ }
126
+ return;
127
+ }
128
+ try {
129
+ process.kill(-child.pid, "SIGTERM");
130
+ return;
131
+ } catch {
132
+ // no such group any more, or a sandbox that refuses signals to a group: each member on its own
133
+ }
134
+ for (const pid of groupMembers(child.pid)) {
135
+ try {
136
+ process.kill(pid, "SIGTERM");
137
+ } catch {
138
+ // already gone
139
+ }
140
+ }
141
+ },
142
+ };
143
+ }
144
+
145
+ /**
146
+ * Open an address in the browser: the program BROWSER names (none: do not open), or the system's opener. Returns
147
+ * whether it tried; the address is printed as well, for a computer without a browser.
148
+ * @param {string} url
149
+ * @param {Record<string, string | undefined>} env
150
+ */
151
+ export function openBrowser(url, env) {
152
+ if (!/^https?:\/\//i.test(url)) return false;
153
+ let command;
154
+ let args;
155
+ if (env.BROWSER) {
156
+ if (env.BROWSER === "none") return false;
157
+ command = env.BROWSER;
158
+ args = [url];
159
+ } else if (process.platform === "darwin") {
160
+ command = "open";
161
+ args = [url];
162
+ } else if (WINDOWS) {
163
+ command = "rundll32";
164
+ args = ["url.dll,FileProtocolHandler", url];
165
+ } else {
166
+ command = "xdg-open";
167
+ args = [url];
168
+ }
169
+ try {
170
+ const child = spawn(command, args, { env, stdio: "ignore", detached: true, windowsHide: true });
171
+ child.on("error", () => {});
172
+ child.unref();
173
+ return true;
174
+ } catch {
175
+ return false;
176
+ }
177
+ }
package/src/project.js ADDED
@@ -0,0 +1,72 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ // What the command tells impact.ai about the folder it runs in, and what it reads from git there.
4
+
5
+ import { spawnSync } from "node:child_process";
6
+ import { existsSync } from "node:fs";
7
+ import { hostname } from "node:os";
8
+ import path from "node:path";
9
+
10
+ /**
11
+ * The application's language, from the manifests in the folder: python, javascript or other.
12
+ * @param {string} folder
13
+ */
14
+ export function detectLanguage(folder) {
15
+ if (["pyproject.toml", "requirements.txt", "setup.py"].some((name) => existsSync(path.join(folder, name)))) {
16
+ return "python";
17
+ }
18
+ if (existsSync(path.join(folder, "package.json"))) return "javascript";
19
+ return "other";
20
+ }
21
+
22
+ /** The computer's host name without its domain, at most 63 characters. */
23
+ export function computerName(name = hostname()) {
24
+ return (name.split(".")[0] || name || "computer").slice(0, 63);
25
+ }
26
+
27
+ /** The folder's base name, at most 100 characters. */
28
+ export function folderName(folder) {
29
+ return (path.basename(path.resolve(folder)) || "folder").slice(0, 100);
30
+ }
31
+
32
+ function git(folder, env, args) {
33
+ const result = spawnSync("git", args, { cwd: folder, env, encoding: "utf8", windowsHide: true });
34
+ if (result.error) return { status: null, stdout: "" };
35
+ return { status: result.status, stdout: result.stdout };
36
+ }
37
+
38
+ /**
39
+ * Where HEAD is, when the folder is in a git repository; null otherwise (or when git is not installed).
40
+ * @returns {{ head: string | null, ref: string | null } | null}
41
+ */
42
+ export function gitState(folder, env) {
43
+ const inside = git(folder, env, ["rev-parse", "--is-inside-work-tree"]);
44
+ if (inside.status !== 0 || inside.stdout.trim() !== "true") return null;
45
+ const head = git(folder, env, ["rev-parse", "--verify", "--quiet", "HEAD"]);
46
+ const ref = git(folder, env, ["symbolic-ref", "--quiet", "HEAD"]);
47
+ return {
48
+ head: head.status === 0 ? head.stdout.trim() : null,
49
+ ref: ref.status === 0 ? ref.stdout.trim() : null,
50
+ };
51
+ }
52
+
53
+ /** How many files git sees as uncommitted (changed, staged or untracked) in the folder's repository. */
54
+ export function uncommittedFiles(folder, env) {
55
+ const status = git(folder, env, ["status", "--porcelain", "--untracked-files=all"]);
56
+ if (status.status !== 0) return 0;
57
+ return status.stdout.split("\n").filter((line) => line.trim()).length;
58
+ }
59
+
60
+ /** Whether git ignores the file; null when git cannot say. */
61
+ export function gitIgnores(folder, env, file) {
62
+ const check = git(folder, env, ["check-ignore", "--quiet", "--", file]);
63
+ if (check.status === 0) return true;
64
+ if (check.status === 1) return false;
65
+ return null;
66
+ }
67
+
68
+ /** Whether HEAD moved, or switched branch, between two readings. */
69
+ export function headMoved(before, after) {
70
+ if (!before || !after) return false;
71
+ return before.head !== after.head || before.ref !== after.ref;
72
+ }
package/src/service.js ADDED
@@ -0,0 +1,99 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ // The client side of the setup protocol with impact.ai, an OAuth 2.0 Device Authorization flow (RFC 8628): start a
4
+ // setup without credentials, collect its result once a signed-in person has allowed it in the browser, then report
5
+ // steps and read the setup's status with the setup token. impact.ai owns the protocol; this client reads only the
6
+ // fields it names and ignores the rest.
7
+
8
+ import { CLIENT } from "./args.js";
9
+
10
+ /** impact.ai could not be reached: no connection, a timeout, or a redirect (never followed, the answers carry secrets). */
11
+ export class Unreachable extends Error {}
12
+
13
+ function why(error) {
14
+ const cause = error?.cause;
15
+ if (cause?.code) return cause.code;
16
+ if (error?.name === "TimeoutError" || error?.name === "AbortError") return "no answer in time";
17
+ return error?.message || "no connection";
18
+ }
19
+
20
+ /**
21
+ * Where the API answers for an app origin. A hosted impact.ai serves its API on the app host's own `api.` host, as the
22
+ * app does; a stack on this computer serves it under the app's `/api` prefix.
23
+ * @param {string} origin the app's origin, as parseOrigin returned it
24
+ * @returns {string} the API's base, ending before `/v1`
25
+ */
26
+ export function apiBase(origin) {
27
+ const url = new URL(origin);
28
+ return url.protocol === "https:" ? `https://api.${url.hostname}${url.port ? `:${url.port}` : ""}` : `${url.origin}/api`;
29
+ }
30
+
31
+ export class Service {
32
+ /**
33
+ * @param {string} origin the app's origin; the API is found from it (apiBase)
34
+ * @param {{ fetch?: typeof fetch, timeoutMs?: number }} [options]
35
+ */
36
+ constructor(origin, { fetch = globalThis.fetch, timeoutMs = 15000 } = {}) {
37
+ this.origin = origin;
38
+ this.base = apiBase(origin);
39
+ this.fetch = fetch;
40
+ this.timeoutMs = timeoutMs;
41
+ }
42
+
43
+ /**
44
+ * @param {string} method
45
+ * @param {string} path
46
+ * @param {{ token?: string, body?: unknown }} [options]
47
+ * @returns {Promise<{ status: number, ok: boolean, body: any }>}
48
+ */
49
+ async request(method, path, { token, body } = {}) {
50
+ const headers = { accept: "application/json", "user-agent": CLIENT };
51
+ if (body !== undefined) headers["content-type"] = "application/json";
52
+ if (token) headers.authorization = `Bearer ${token}`;
53
+ let response;
54
+ try {
55
+ response = await this.fetch(new URL(`${this.base}${path}`), {
56
+ method,
57
+ headers,
58
+ body: body === undefined ? undefined : JSON.stringify(body),
59
+ redirect: "error",
60
+ signal: AbortSignal.timeout(this.timeoutMs),
61
+ });
62
+ } catch (error) {
63
+ throw new Unreachable(why(error));
64
+ }
65
+ let text = "";
66
+ try {
67
+ text = await response.text();
68
+ } catch (error) {
69
+ throw new Unreachable(why(error));
70
+ }
71
+ let parsed = null;
72
+ try {
73
+ parsed = text ? JSON.parse(text) : null;
74
+ } catch {
75
+ parsed = null;
76
+ }
77
+ return { status: response.status, ok: response.ok, body: parsed };
78
+ }
79
+
80
+ /** 1. Start a setup: `{ computer, folder, language, client }`, answered 201 with the device code and the allow URL. */
81
+ start({ computer, folder, language }) {
82
+ return this.request("POST", "/v1/setups", { body: { computer, folder, language, client: CLIENT } });
83
+ }
84
+
85
+ /** 3. Collect: always 200 with a status, and the result exactly once. */
86
+ collect(deviceCode) {
87
+ return this.request("POST", "/v1/setups/token", { body: { deviceCode } });
88
+ }
89
+
90
+ /** 4. Report a step with the setup token: 204. */
91
+ report(setupId, token, step) {
92
+ return this.request("POST", `/v1/setups/${encodeURIComponent(setupId)}/steps`, { token, body: step });
93
+ }
94
+
95
+ /** 5. The setup's status with the setup token. */
96
+ status(setupId, token) {
97
+ return this.request("GET", `/v1/setups/${encodeURIComponent(setupId)}`, { token });
98
+ }
99
+ }
@@ -0,0 +1,134 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ // What the person sees and answers. Everything printed passes through the redaction of the secrets the command holds,
4
+ // so that the ingest key never reaches the terminal, even when an agent or the application prints it.
5
+
6
+ const REDACTED = "[ingest key]";
7
+
8
+ /** Reads a stream one line at a time; null once it has ended. */
9
+ class Lines {
10
+ constructor(stream) {
11
+ this.stream = stream;
12
+ this.buffer = "";
13
+ this.queue = [];
14
+ this.waiting = [];
15
+ this.ended = false;
16
+ this.started = false;
17
+ }
18
+
19
+ begin() {
20
+ if (this.started) return;
21
+ this.started = true;
22
+ this.stream.setEncoding?.("utf8");
23
+ this.stream.on("data", (chunk) => {
24
+ this.buffer += chunk;
25
+ let at = this.buffer.indexOf("\n");
26
+ while (at !== -1) {
27
+ this.push(this.buffer.slice(0, at).replace(/\r$/, ""));
28
+ this.buffer = this.buffer.slice(at + 1);
29
+ at = this.buffer.indexOf("\n");
30
+ }
31
+ });
32
+ this.stream.on("end", () => {
33
+ if (this.buffer) this.push(this.buffer);
34
+ this.buffer = "";
35
+ this.ended = true;
36
+ for (const resolve of this.waiting.splice(0)) resolve(null);
37
+ });
38
+ this.stream.on("error", () => {
39
+ this.ended = true;
40
+ for (const resolve of this.waiting.splice(0)) resolve(null);
41
+ });
42
+ }
43
+
44
+ push(line) {
45
+ const resolve = this.waiting.shift();
46
+ if (resolve) resolve(line);
47
+ else this.queue.push(line);
48
+ }
49
+
50
+ next() {
51
+ this.begin();
52
+ if (this.queue.length) return Promise.resolve(this.queue.shift());
53
+ if (this.ended) return Promise.resolve(null);
54
+ this.stream.resume?.();
55
+ return new Promise((resolve) => this.waiting.push(resolve));
56
+ }
57
+
58
+ close() {
59
+ if (this.started) this.stream.pause?.();
60
+ }
61
+ }
62
+
63
+ export class Terminal {
64
+ /**
65
+ * @param {{ stdin: NodeJS.ReadableStream, stdout: NodeJS.WritableStream, stderr: NodeJS.WritableStream,
66
+ * yes: boolean }} io
67
+ */
68
+ constructor({ stdin, stdout, stderr, yes }) {
69
+ this.stdout = stdout;
70
+ this.stderr = stderr;
71
+ this.yes = yes;
72
+ this.lines = new Lines(stdin);
73
+ this.secrets = [];
74
+ }
75
+
76
+ /** Never print this value again. */
77
+ secret(value) {
78
+ if (typeof value === "string" && value.length >= 4 && !this.secrets.includes(value)) this.secrets.push(value);
79
+ }
80
+
81
+ redact(text) {
82
+ let out = String(text);
83
+ for (const secret of this.secrets) out = out.split(secret).join(REDACTED);
84
+ return out;
85
+ }
86
+
87
+ line(text = "") {
88
+ this.stdout.write(`${this.redact(text)}\n`);
89
+ }
90
+
91
+ error(text) {
92
+ this.stderr.write(`${this.redact(text)}\n`);
93
+ }
94
+
95
+ /** A line of another program's output, indented under the command's own. */
96
+ quote(text) {
97
+ this.stdout.write(` | ${this.redact(text)}\n`);
98
+ }
99
+
100
+ /**
101
+ * A yes-or-no question. --yes answers yes; an ended input (no terminal) answers no.
102
+ * @param {string} question
103
+ * @param {{ defaultYes?: boolean }} [options]
104
+ */
105
+ async confirm(question, { defaultYes = false } = {}) {
106
+ const hint = defaultYes ? "[Y/n]" : "[y/N]";
107
+ if (this.yes) {
108
+ this.line(`${question} ${hint} yes (--yes)`);
109
+ return true;
110
+ }
111
+ this.stdout.write(`${this.redact(question)} ${hint} `);
112
+ const answer = await this.lines.next();
113
+ if (answer === null) {
114
+ this.line("");
115
+ this.line("No answer (no terminal): taken as no. Run with --yes to answer yes without a terminal.");
116
+ return false;
117
+ }
118
+ const word = answer.trim().toLowerCase();
119
+ if (word === "") return defaultYes;
120
+ return word === "y" || word === "yes";
121
+ }
122
+
123
+ /** A line of text the person types; null without an answer, and with --yes (nobody to type it). */
124
+ async ask(question) {
125
+ if (this.yes) return null;
126
+ this.stdout.write(`${this.redact(question)} `);
127
+ const answer = await this.lines.next();
128
+ return answer === null ? null : answer.trim() || null;
129
+ }
130
+
131
+ close() {
132
+ this.lines.close();
133
+ }
134
+ }