@engini/cli 0.12.1 → 0.14.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.
Files changed (3) hide show
  1. package/README.md +27 -1
  2. package/dist/cli.js +292 -32
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -16,7 +16,7 @@ npx @engini/cli --help
16
16
  ## Quickstart
17
17
 
18
18
  ```bash
19
- engini login --api-key eng_… # or run interactively on a TTY
19
+ engini login --api-key eng_… # or bare `engini login` to paste it interactively
20
20
  engini applications list --available # discover connector apps
21
21
  engini tools list --application monday # discover tools
22
22
  engini tools call monday_create_item --args '{}' --connection 3
@@ -93,6 +93,22 @@ with `--json`. Every command also accepts:
93
93
  Exit codes are a stable contract: `0` success · `1` general error · `2` usage error ·
94
94
  `3` authentication error · `4` not found · `5` validation error · `124` timeout.
95
95
 
96
+ Interactive prompts, specifically:
97
+
98
+ - **Declining** a confirmation (`[y/N]` → `n`) exits **`0`** — you asked, the answer
99
+ was no, nothing went wrong.
100
+ - **Aborting** a prompt with Ctrl-C or Ctrl-D exits **`2`**, as does stdin ending
101
+ before you answered. A cancelled prompt makes no claim about what a
102
+ partly-completed command already did — `connect`, for instance, may already have
103
+ created the connection server-side.
104
+ - A command that needs to prompt but **can't** exits `2`. Prompting requires a
105
+ terminal on *both* stdin and stdout; pass the values as flags (`--api-key`,
106
+ `--field`, `--force`) when either is piped. `connect`'s resumable gates
107
+ behave the same way: with stdin piped they emit their `need:` payload and exit
108
+ `5` rather than prompting. Note the payload is pretty-printed rather than JSON
109
+ when stdout is a terminal — output formatting follows stdout, interactivity
110
+ follows both streams.
111
+
96
112
  ## Large results (token economy)
97
113
 
98
114
  Tool outputs can be huge — an agent shouldn't pay tokens for data it hasn't asked
@@ -130,4 +146,14 @@ Credentials and host config live in `$XDG_CONFIG_HOME/engini/config.toml`
130
146
  **flags > environment > config**; the env vars are `ENGINI_API_KEY` (preferred) or
131
147
  `ENGINI_API_TOKEN`, plus `ENGINI_COMPANY_TOKEN`.
132
148
 
149
+ ### `engini login`
150
+
151
+ An API key must start with `eng_`. A malformed, empty, or line-broken key exits
152
+ `2` and writes nothing — that applies equally to `--api-key` and to the
153
+ interactive prompt, which re-asks up to three times.
154
+
155
+ Interactive entry needs a terminal on **both** stdin and stdout. If stdin is
156
+ piped (CI, a wrapper script), pass `--api-key` — `engini login` with a redirected
157
+ stdin exits `2` rather than prompting into the void.
158
+
133
159
  Source & docs: <https://github.com/engini/engini-sdk>
package/dist/cli.js CHANGED
@@ -14,8 +14,29 @@ function openBrowser(url) {
14
14
  } catch {
15
15
  }
16
16
  }
17
+ var PromptCancelled = class extends Error {
18
+ constructor() {
19
+ super("cancelled");
20
+ this.name = "PromptCancelled";
21
+ }
22
+ };
23
+ var PromptStreamEnded = class extends Error {
24
+ constructor() {
25
+ super("stdin ended before an answer was given");
26
+ this.name = "PromptStreamEnded";
27
+ }
28
+ };
17
29
  function ask(rl, question) {
18
- return new Promise((resolve) => rl.question(question, resolve));
30
+ return new Promise((resolve, reject) => {
31
+ let answered = false;
32
+ rl.question(question, (value) => {
33
+ answered = true;
34
+ resolve(value);
35
+ });
36
+ rl.once("close", () => {
37
+ if (!answered) reject(new PromptStreamEnded());
38
+ });
39
+ });
19
40
  }
20
41
  async function confirm(question) {
21
42
  const rl = createInterface({ input: process.stdin, output: process.stdout });
@@ -36,23 +57,150 @@ async function promptText(label, fallback = "") {
36
57
  rl.close();
37
58
  }
38
59
  }
39
- async function promptHidden(label) {
40
- const output = process.stdout;
41
- const rl = createInterface({ input: process.stdin, output, terminal: true });
42
- let muted = false;
43
- const realWrite = output.write.bind(output);
44
- rl._writeToOutput = (s) => {
45
- if (!muted) realWrite(s);
46
- };
47
- output.write(`${label}: `);
48
- muted = true;
49
- try {
50
- const value = await ask(rl, "");
51
- realWrite("\n");
52
- return value.trim();
53
- } finally {
54
- rl.close();
60
+ var ESC = "\x1B";
61
+ var CTRL_C = "";
62
+ var CTRL_D = "";
63
+ var CTRL_U = "";
64
+ var DEL = "\x7F";
65
+ var BACKSPACE = "\b";
66
+ var MAX_ESCAPE_LENGTH = 256;
67
+ function escapeKind(pending) {
68
+ if (pending.length < 2) return "incomplete";
69
+ const second = pending[1];
70
+ if (second !== "[" && second !== "O") return "two-char";
71
+ if (pending.length < 3) return "incomplete";
72
+ const last = pending[pending.length - 1];
73
+ return last >= "@" && last <= "~" ? "csi" : "incomplete";
74
+ }
75
+ function promptHidden(label, opts = {}) {
76
+ const streams = opts.streams ?? { input: process.stdin, output: process.stdout };
77
+ const { input, output } = streams;
78
+ const wasRaw = Boolean(input.isRaw);
79
+ let raw = false;
80
+ if (input.isTTY && typeof input.setRawMode === "function") {
81
+ try {
82
+ input.setRawMode(true);
83
+ raw = true;
84
+ } catch {
85
+ raw = false;
86
+ }
55
87
  }
88
+ const mask = (opts.mask ?? true) && raw;
89
+ return new Promise((resolve, reject) => {
90
+ let settled = false;
91
+ const write = (s) => {
92
+ try {
93
+ output.write(s);
94
+ } catch {
95
+ }
96
+ };
97
+ let restored = false;
98
+ const restore = () => {
99
+ if (restored) return;
100
+ restored = true;
101
+ try {
102
+ if (raw) input.setRawMode?.(wasRaw);
103
+ } catch {
104
+ }
105
+ try {
106
+ input.pause();
107
+ } catch {
108
+ }
109
+ };
110
+ const usingRealStdin = input === process.stdin;
111
+ if (usingRealStdin) process.once("exit", restore);
112
+ const detach = () => {
113
+ input.removeListener("data", onData);
114
+ input.removeListener("end", onEnd);
115
+ input.removeListener("error", onEnd);
116
+ if (usingRealStdin) process.removeListener("exit", restore);
117
+ };
118
+ const finish = (err, result) => {
119
+ if (settled) return;
120
+ settled = true;
121
+ detach();
122
+ restore();
123
+ write("\n");
124
+ if (err) reject(err);
125
+ else resolve(result);
126
+ };
127
+ function onEnd() {
128
+ finish(new PromptStreamEnded());
129
+ }
130
+ let buf = "";
131
+ let pending = "";
132
+ const eraseOne = () => {
133
+ const cps = Array.from(buf);
134
+ cps.pop();
135
+ buf = cps.join("");
136
+ };
137
+ const clearLine = () => {
138
+ if (mask) write("\b \b".repeat(Array.from(buf).length));
139
+ buf = "";
140
+ };
141
+ const onData = (chunk) => {
142
+ const chars = Array.from(chunk);
143
+ let discarding = false;
144
+ for (let i = 0; i < chars.length; i++) {
145
+ const ch = chars[i];
146
+ if (ch === CTRL_C || ch === CTRL_D) return finish(new PromptCancelled());
147
+ if (ch === "\r" || ch === "\n") {
148
+ const rest = chars.slice(i + 1).join("");
149
+ return finish(null, { value: buf.trim(), truncated: rest.trim().length > 0 });
150
+ }
151
+ if (discarding) continue;
152
+ if (pending) {
153
+ pending += ch;
154
+ if (pending.length > MAX_ESCAPE_LENGTH) {
155
+ clearLine();
156
+ pending = "";
157
+ discarding = true;
158
+ continue;
159
+ }
160
+ const kind = escapeKind(pending);
161
+ if (kind === "csi") {
162
+ pending = "";
163
+ } else if (kind === "two-char") {
164
+ if (pending[1] === ESC) {
165
+ pending = ESC;
166
+ continue;
167
+ }
168
+ clearLine();
169
+ pending = "";
170
+ }
171
+ continue;
172
+ }
173
+ if (ch === ESC) {
174
+ pending = ch;
175
+ continue;
176
+ }
177
+ if (ch === DEL || ch === BACKSPACE) {
178
+ if (buf.length > 0) {
179
+ eraseOne();
180
+ if (mask) write("\b \b");
181
+ }
182
+ continue;
183
+ }
184
+ if (ch === CTRL_U) {
185
+ clearLine();
186
+ continue;
187
+ }
188
+ if (ch < " ") continue;
189
+ buf += ch;
190
+ if (mask) write("*");
191
+ }
192
+ };
193
+ try {
194
+ input.resume();
195
+ input.setEncoding("utf8");
196
+ write(`${label}: `);
197
+ input.on("data", onData);
198
+ input.on("end", onEnd);
199
+ input.on("error", onEnd);
200
+ } catch (err) {
201
+ finish(err instanceof Error ? err : new Error(String(err)));
202
+ }
203
+ });
56
204
  }
57
205
 
58
206
  // src/conventions.ts
@@ -85,6 +233,9 @@ var CliError = class extends Error {
85
233
  function isTty() {
86
234
  return Boolean(process.stdout.isTTY);
87
235
  }
236
+ function isInteractive() {
237
+ return Boolean(process.stdout.isTTY && process.stdin.isTTY);
238
+ }
88
239
  var context = { forceJson: false, quiet: false, dryRun: false };
89
240
  function setOutputContext(ctx) {
90
241
  context = ctx;
@@ -144,7 +295,7 @@ function maskSecret(value) {
144
295
  }
145
296
  async function confirmOrFail(prompt, opts) {
146
297
  if (opts.force) return;
147
- if (isTty()) {
298
+ if (isInteractive()) {
148
299
  if (!await confirm(prompt)) {
149
300
  throw new CliError(0 /* OK */);
150
301
  }
@@ -198,7 +349,21 @@ async function runCommand(command, opts, mutating, body) {
198
349
  quiet: Boolean(opts.quiet),
199
350
  dryRun: Boolean(opts.dryRun)
200
351
  });
201
- await body();
352
+ try {
353
+ await body();
354
+ } catch (err) {
355
+ if (err instanceof PromptCancelled) {
356
+ fail(2 /* USAGE */, "Cancelled.");
357
+ }
358
+ if (err instanceof PromptStreamEnded) {
359
+ fail(
360
+ 2 /* USAGE */,
361
+ "Input ended before the prompt was answered.",
362
+ "Pass the required values as flags when running non-interactively."
363
+ );
364
+ }
365
+ throw err;
366
+ }
202
367
  }
203
368
 
204
369
  // src/main.ts
@@ -580,7 +745,7 @@ async function chooseAuth(methods, auth, application) {
580
745
  return chosen;
581
746
  }
582
747
  if (methods.length === 1) return methods[0];
583
- if (isTty()) {
748
+ if (isInteractive()) {
584
749
  for (const m of methods) {
585
750
  console.error(` ${m.authenticationId}: ${m.authenticationName} (${m.authenticationType})`);
586
751
  }
@@ -597,16 +762,27 @@ async function chooseAuth(methods, auth, application) {
597
762
  });
598
763
  }
599
764
  async function collectFields(method, application, field) {
765
+ async function readSecretField(label) {
766
+ const { value, truncated } = await promptHidden(label);
767
+ if (truncated) {
768
+ fail(
769
+ 2 /* USAGE */,
770
+ `${label} contained a line break - only the first line was captured.`,
771
+ `Pass it directly instead: --field <name>=<value>`
772
+ );
773
+ }
774
+ return value;
775
+ }
600
776
  const provided = parseFields(field);
601
777
  const schema = method.connectionFields.filter((f) => !f.isHidden);
602
778
  const required = schema.filter((f) => f.isRequired);
603
779
  const missing = required.filter((f) => !(f.fieldName in provided));
604
780
  if (missing.length === 0) return provided;
605
- if (isTty()) {
781
+ if (isInteractive()) {
606
782
  for (const f of schema) {
607
783
  if (f.fieldName in provided) continue;
608
784
  const label = fieldLabel(f);
609
- const value = f.isPassword ? await promptHidden(label) : await promptText(label, clean(f.defaultValue) ?? "");
785
+ const value = f.isPassword ? await readSecretField(label) : await promptText(label, clean(f.defaultValue) ?? "");
610
786
  if (value) provided[f.fieldName] = value;
611
787
  }
612
788
  return provided;
@@ -623,7 +799,7 @@ async function collectFields(method, application, field) {
623
799
  async function resolveName(name, application) {
624
800
  if (name) return name;
625
801
  const fallback = `${application} connection`;
626
- if (isTty()) return promptText("Connection name", fallback);
802
+ if (isInteractive()) return promptText("Connection name", fallback);
627
803
  return fallback;
628
804
  }
629
805
  async function selectObjectStep(client, application, connectionId, objectSpecs, opts) {
@@ -641,7 +817,7 @@ async function selectObjectStep(client, application, connectionId, objectSpecs,
641
817
  }
642
818
  async function resolveObjects(objs, connectionId, application) {
643
819
  if (objs.length === 0) return [];
644
- if (isTty()) {
820
+ if (isInteractive()) {
645
821
  for (const o of objs) console.error(` ${o.objectId}: ${o.name} (${o.type})`);
646
822
  const raw = await promptText("Object ids to select (comma/space separated, blank for none)");
647
823
  return raw.split(/[\s,]+/).filter(Boolean).map(Number).filter(Number.isInteger);
@@ -1151,6 +1327,8 @@ CORE COMMANDS
1151
1327
 
1152
1328
  ACCOUNT
1153
1329
  login Store an opaque Engini API key (eng_\u2026): --api-key, or interactive on a TTY.
1330
+ The key must start with "eng_"; a malformed or empty one exits 2 and
1331
+ stores nothing. Interactive entry needs a terminal on stdin AND stdout.
1154
1332
  logout Clear the stored credentials.
1155
1333
  whoami Show the authenticated user/company.
1156
1334
 
@@ -1241,7 +1419,12 @@ var EXAMPLES = {
1241
1419
  login: `Examples:
1242
1420
  engini login --api-key eng_\u2026 # store a key non-interactively
1243
1421
  engini login --api-url https://staging.engini.io # point at another environment
1244
- engini login --api-key eng_\u2026 --dry-run # preview without writing`,
1422
+ engini login --api-key eng_\u2026 --dry-run # preview without writing
1423
+ engini login # interactive: paste the key when prompted
1424
+
1425
+ The key must start with "eng_". A malformed or empty key exits 2 without writing
1426
+ anything, on either path. Interactive entry needs a terminal on both stdin and
1427
+ stdout \u2014 pipe stdin (e.g. in CI) and you must pass --api-key.`,
1245
1428
  "tools list": `Examples:
1246
1429
  engini tools list --application monday --limit 5
1247
1430
  engini tools list | jq -r '.[].tool_slug'
@@ -1303,22 +1486,99 @@ function installHelp(program) {
1303
1486
  function keysUrl(config) {
1304
1487
  return `${config.identity_url.replace(/\/+$/, "")}/users`;
1305
1488
  }
1489
+ var MAX_KEY_ATTEMPTS = 3;
1490
+ function charCount(key) {
1491
+ return Array.from(key).length;
1492
+ }
1493
+ function keyProblem(key, truncated = false) {
1494
+ if (truncated) return "Your paste contained a line break - only the first line was captured.";
1495
+ if (!key) return "Nothing pasted.";
1496
+ if (!key.startsWith("eng_")) {
1497
+ return 'That does not look like an Engini key - expected an "eng_" prefix.';
1498
+ }
1499
+ return null;
1500
+ }
1501
+ async function askForKey(url) {
1502
+ console.log("");
1503
+ console.log("Paste your API key below - it will not be echoed.");
1504
+ console.log(`Create or copy one at ${url}`);
1505
+ console.log("");
1506
+ for (let attempt = 1; ; attempt++) {
1507
+ let key;
1508
+ let truncated;
1509
+ try {
1510
+ ({ value: key, truncated } = await promptHidden(" API key"));
1511
+ } catch (err) {
1512
+ if (err instanceof PromptCancelled) fail(2 /* USAGE */, "Cancelled \u2014 no credentials stored.");
1513
+ if (err instanceof PromptStreamEnded) {
1514
+ fail(
1515
+ 2 /* USAGE */,
1516
+ "Input ended before a key was entered.",
1517
+ "Pass the key directly instead: engini login --api-key eng_\u2026"
1518
+ );
1519
+ }
1520
+ throw err;
1521
+ }
1522
+ const problem = keyProblem(key, truncated);
1523
+ if (!problem) {
1524
+ console.log(` \u2713 Received ${charCount(key)} characters \u2014 ${maskSecret(key)}`);
1525
+ console.log("");
1526
+ return key;
1527
+ }
1528
+ if (attempt >= MAX_KEY_ATTEMPTS) {
1529
+ fail(
1530
+ 2 /* USAGE */,
1531
+ `${problem} Giving up after ${MAX_KEY_ATTEMPTS} attempts.`,
1532
+ `Pass the key directly instead: engini login --api-key eng_\u2026 (create one at ${url})`
1533
+ );
1534
+ }
1535
+ console.log(` ! ${problem} Try again, or press Ctrl-C to cancel.`);
1536
+ console.log("");
1537
+ }
1538
+ }
1306
1539
  async function loginBody(opts) {
1307
1540
  const config = loadConfig();
1308
1541
  const hadCredentials = Boolean(config.api_key || config.api_token);
1309
1542
  if (opts.apiUrl) config.api_url = opts.apiUrl;
1310
1543
  if (opts.identityUrl) config.identity_url = opts.identityUrl;
1311
- let apiKey = opts.apiKey;
1544
+ let apiKey = opts.apiKey?.trim();
1545
+ if (opts.apiKey !== void 0) {
1546
+ const problem = keyProblem(apiKey ?? "");
1547
+ if (problem) {
1548
+ fail(
1549
+ 2 /* USAGE */,
1550
+ `--api-key ${apiKey ? "is not a valid Engini key" : "was empty"}. ${problem}`,
1551
+ "Pass the key value: engini login --api-key eng_\u2026"
1552
+ );
1553
+ }
1554
+ }
1312
1555
  if (!apiKey) {
1313
- if (!isTty()) {
1314
- fail(2 /* USAGE */, "Provide --api-key when running non-interactively.");
1556
+ if (!isInteractive()) {
1557
+ fail(
1558
+ 2 /* USAGE */,
1559
+ "Provide --api-key when running non-interactively.",
1560
+ "Interactive login needs a terminal on both stdin and stdout."
1561
+ );
1562
+ }
1563
+ const url = keysUrl(config);
1564
+ let hasKey;
1565
+ try {
1566
+ hasKey = await confirm("Do you already have an Engini API key?");
1567
+ } catch (err) {
1568
+ if (err instanceof PromptStreamEnded) {
1569
+ fail(
1570
+ 2 /* USAGE */,
1571
+ "Input ended before the question was answered.",
1572
+ "Pass the key directly instead: engini login --api-key eng_\u2026"
1573
+ );
1574
+ }
1575
+ throw err;
1315
1576
  }
1316
- if (!await confirm("Do you already have an Engini API key?")) {
1317
- const url = keysUrl(config);
1577
+ if (!hasKey) {
1318
1578
  console.log(`Opening ${url} \u2014 create a key there, then paste it below.`);
1319
1579
  openBrowser(url);
1320
1580
  }
1321
- apiKey = await promptHidden("Paste your API key (eng_\u2026)");
1581
+ apiKey = await askForKey(url);
1322
1582
  }
1323
1583
  config.api_key = apiKey;
1324
1584
  config.auth_kind = "api-key";
@@ -2345,7 +2605,7 @@ function registerWhoami(program) {
2345
2605
  }
2346
2606
 
2347
2607
  // src/version.ts
2348
- var VERSION = true ? "0.12.1" : "0.0.0";
2608
+ var VERSION = true ? "0.14.0" : "0.0.0";
2349
2609
 
2350
2610
  // src/main.ts
2351
2611
  function buildProgram() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@engini/cli",
3
- "version": "0.12.1",
3
+ "version": "0.14.0",
4
4
  "description": "Engini CLI — machine-first command line over the Engini Public API",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -24,7 +24,7 @@
24
24
  "test": "vitest run"
25
25
  },
26
26
  "dependencies": {
27
- "@engini/sdk": "^0.12.1",
27
+ "@engini/sdk": "^0.14.0",
28
28
  "commander": "^12.1.0",
29
29
  "smol-toml": "^1.3.0"
30
30
  },