@engini/cli 0.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.
Files changed (2) hide show
  1. package/dist/cli.js +963 -0
  2. package/package.json +34 -0
package/dist/cli.js ADDED
@@ -0,0 +1,963 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/prompt.ts
4
+ import { spawn } from "child_process";
5
+ import { createInterface } from "readline";
6
+ function openBrowser(url) {
7
+ const command = process.platform === "win32" ? "start" : process.platform === "darwin" ? "open" : "xdg-open";
8
+ const args = process.platform === "win32" ? ["", url] : [url];
9
+ try {
10
+ const child = spawn(command, args, { stdio: "ignore", detached: true, shell: process.platform === "win32" });
11
+ child.on("error", () => {
12
+ });
13
+ child.unref();
14
+ } catch {
15
+ }
16
+ }
17
+ function ask(rl, question) {
18
+ return new Promise((resolve) => rl.question(question, resolve));
19
+ }
20
+ async function confirm(question) {
21
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
22
+ try {
23
+ const answer = (await ask(rl, `${question} [y/N] `)).trim().toLowerCase();
24
+ return answer === "y" || answer === "yes";
25
+ } finally {
26
+ rl.close();
27
+ }
28
+ }
29
+ async function promptHidden(label) {
30
+ const output = process.stdout;
31
+ const rl = createInterface({ input: process.stdin, output, terminal: true });
32
+ let muted = false;
33
+ const realWrite = output.write.bind(output);
34
+ rl._writeToOutput = (s) => {
35
+ if (!muted) realWrite(s);
36
+ };
37
+ output.write(`${label}: `);
38
+ muted = true;
39
+ try {
40
+ const value = await ask(rl, "");
41
+ realWrite("\n");
42
+ return value.trim();
43
+ } finally {
44
+ rl.close();
45
+ }
46
+ }
47
+
48
+ // src/conventions.ts
49
+ var Exit = /* @__PURE__ */ ((Exit2) => {
50
+ Exit2[Exit2["OK"] = 0] = "OK";
51
+ Exit2[Exit2["GENERIC"] = 1] = "GENERIC";
52
+ Exit2[Exit2["USAGE"] = 2] = "USAGE";
53
+ Exit2[Exit2["AUTH"] = 3] = "AUTH";
54
+ Exit2[Exit2["NOT_FOUND"] = 4] = "NOT_FOUND";
55
+ Exit2[Exit2["VALIDATION"] = 5] = "VALIDATION";
56
+ Exit2[Exit2["TIMEOUT"] = 124] = "TIMEOUT";
57
+ return Exit2;
58
+ })(Exit || {});
59
+ var ERROR_NAMES = {
60
+ [1 /* GENERIC */]: "Error",
61
+ [2 /* USAGE */]: "UsageError",
62
+ [3 /* AUTH */]: "AuthError",
63
+ [4 /* NOT_FOUND */]: "ResourceNotFound",
64
+ [5 /* VALIDATION */]: "ValidationError",
65
+ [124 /* TIMEOUT */]: "Timeout"
66
+ };
67
+ var CliError = class extends Error {
68
+ constructor(code) {
69
+ super(`CliExit(${code})`);
70
+ this.code = code;
71
+ this.name = "CliError";
72
+ }
73
+ code;
74
+ };
75
+ function isTty() {
76
+ return Boolean(process.stdout.isTTY);
77
+ }
78
+ var context = { forceJson: false, quiet: false, dryRun: false };
79
+ function setOutputContext(ctx) {
80
+ context = ctx;
81
+ }
82
+ function dryRun() {
83
+ return context.dryRun;
84
+ }
85
+ function formatValue(value) {
86
+ return typeof value === "string" ? value : JSON.stringify(value);
87
+ }
88
+ function pretty(obj) {
89
+ if (obj !== null && typeof obj === "object" && !Array.isArray(obj)) {
90
+ for (const [key, value] of Object.entries(obj)) {
91
+ console.log(`${key}: ${formatValue(value)}`);
92
+ }
93
+ } else if (Array.isArray(obj)) {
94
+ for (const item of obj) {
95
+ console.log(formatValue(item));
96
+ }
97
+ } else {
98
+ console.log(formatValue(obj));
99
+ }
100
+ }
101
+ function printOutput(obj) {
102
+ if (context.forceJson) {
103
+ console.log(JSON.stringify(obj, null, 2));
104
+ } else if (!isTty()) {
105
+ console.log(JSON.stringify(obj));
106
+ } else {
107
+ pretty(obj);
108
+ }
109
+ }
110
+ function fail(code, message, hint) {
111
+ if (isTty()) {
112
+ console.error(`Error: ${message}`);
113
+ if (hint) console.error(`Hint: ${hint}`);
114
+ } else {
115
+ const payload = {
116
+ error: ERROR_NAMES[code] ?? "Error",
117
+ message,
118
+ exit_code: code
119
+ };
120
+ if (hint) payload.hint = hint;
121
+ console.error(JSON.stringify(payload));
122
+ }
123
+ throw new CliError(code);
124
+ }
125
+ function notImplemented(commandName) {
126
+ return fail(1 /* GENERIC */, `Command '${commandName}' is scaffolded but not yet implemented`);
127
+ }
128
+ function maskSecret(value) {
129
+ return value.length > 8 ? `${value.slice(0, 4)}\u2026${value.slice(-4)}` : "****";
130
+ }
131
+ async function confirmOrFail(prompt, opts) {
132
+ if (opts.force) return;
133
+ if (isTty()) {
134
+ if (!await confirm(prompt)) {
135
+ throw new CliError(0 /* OK */);
136
+ }
137
+ return;
138
+ }
139
+ fail(2 /* USAGE */, `${prompt} Pass --force to proceed non-interactively.`);
140
+ }
141
+ var SCHEMA_VERSION = "1";
142
+ var UNIVERSAL_FLAGS = /* @__PURE__ */ new Set(["--json", "--quiet", "--schema", "--dry-run"]);
143
+ function schemaKey(name) {
144
+ return name.replace(/^--?/, "").replace(/-/g, "_");
145
+ }
146
+ function optionTakesValue(option) {
147
+ return option.required || option.optional;
148
+ }
149
+ function buildSchema(command, mutating) {
150
+ const args = {};
151
+ for (const arg of command.registeredArguments) {
152
+ args[schemaKey(arg.name())] = { type: "string", required: arg.required };
153
+ }
154
+ for (const option of command.options) {
155
+ if (UNIVERSAL_FLAGS.has(option.long ?? "")) continue;
156
+ const key = schemaKey(option.long ?? option.short ?? "");
157
+ args[key] = {
158
+ type: optionTakesValue(option) ? "string" : "boolean",
159
+ required: option.mandatory
160
+ };
161
+ }
162
+ return {
163
+ $schema: "https://json-schema.org/draft/2020-12/schema",
164
+ version: SCHEMA_VERSION,
165
+ mutating,
166
+ args,
167
+ output: null
168
+ };
169
+ }
170
+ function addUniversalOptions(command, opts = {}) {
171
+ command.option("--json", "Pretty JSON output").option("--quiet", "Suppress non-essential output").option("--schema", "Print this command's args/output schema as JSON");
172
+ if (opts.mutating) {
173
+ command.option("--dry-run", "Preview without executing");
174
+ }
175
+ return command;
176
+ }
177
+ async function runCommand(command, opts, mutating, body) {
178
+ if (opts.schema) {
179
+ console.log(JSON.stringify(buildSchema(command, mutating), null, 2));
180
+ throw new CliError(0 /* OK */);
181
+ }
182
+ setOutputContext({
183
+ forceJson: Boolean(opts.json),
184
+ quiet: Boolean(opts.quiet),
185
+ dryRun: Boolean(opts.dryRun)
186
+ });
187
+ await body();
188
+ }
189
+
190
+ // src/main.ts
191
+ import { Command } from "commander";
192
+
193
+ // src/http.ts
194
+ import {
195
+ Engini,
196
+ ENV_API_KEY_VAR,
197
+ ENV_COMPANY_TOKEN_VAR,
198
+ ENV_TOKEN_VAR,
199
+ EnginiAuthError,
200
+ EnginiError,
201
+ EnginiNotFoundError,
202
+ EnginiValidationError
203
+ } from "@engini/sdk";
204
+
205
+ // src/config.ts
206
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
207
+ import { homedir } from "os";
208
+ import { dirname, join } from "path";
209
+ import { parse, stringify } from "smol-toml";
210
+ var CONFIG_SCHEMA_VERSION = 1;
211
+ function defaultConfig() {
212
+ return {
213
+ config_schema_version: CONFIG_SCHEMA_VERSION,
214
+ api_url: "https://api.engini.io",
215
+ identity_url: "https://app.engini.io"
216
+ };
217
+ }
218
+ function configPath() {
219
+ const base = process.platform === "win32" ? process.env.APPDATA ?? homedir() : process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config");
220
+ return join(base, "engini", "config.toml");
221
+ }
222
+ function asString(value) {
223
+ return typeof value === "string" ? value : void 0;
224
+ }
225
+ function loadConfig(path = configPath()) {
226
+ if (!existsSync(path)) return defaultConfig();
227
+ const data = parse(readFileSync(path, "utf8"));
228
+ const config = defaultConfig();
229
+ if (typeof data.config_schema_version === "number") {
230
+ config.config_schema_version = data.config_schema_version;
231
+ }
232
+ config.api_url = asString(data.api_url) ?? config.api_url;
233
+ config.identity_url = asString(data.identity_url) ?? config.identity_url;
234
+ config.api_key = asString(data.api_key);
235
+ config.api_token = asString(data.api_token);
236
+ config.company_token = asString(data.company_token);
237
+ if (data.auth_kind === "api-key" || data.auth_kind === "jwt") {
238
+ config.auth_kind = data.auth_kind;
239
+ }
240
+ return config;
241
+ }
242
+ function saveConfig(config, path = configPath()) {
243
+ mkdirSync(dirname(path), { recursive: true });
244
+ const data = {};
245
+ for (const [key, value] of Object.entries(config)) {
246
+ if (value !== void 0) data[key] = value;
247
+ }
248
+ writeFileSync(path, stringify(data), { mode: 384 });
249
+ if (process.platform !== "win32") chmodSync(path, 384);
250
+ }
251
+
252
+ // src/http.ts
253
+ function buildClient(overrides = {}) {
254
+ const config = loadConfig();
255
+ const key = overrides.apiKey ?? process.env[ENV_API_KEY_VAR] ?? config.api_key;
256
+ if (key) {
257
+ return new Engini({ apiKey: key, baseUrl: config.api_url });
258
+ }
259
+ const token = overrides.apiToken ?? process.env[ENV_TOKEN_VAR] ?? config.api_token;
260
+ const company = overrides.companyToken ?? process.env[ENV_COMPANY_TOKEN_VAR] ?? config.company_token;
261
+ if (!token) {
262
+ fail(3 /* AUTH */, "No credentials found. Run `engini login`.");
263
+ }
264
+ return new Engini({ token, companyToken: company, baseUrl: config.api_url });
265
+ }
266
+ function exitForError(err) {
267
+ if (err instanceof EnginiAuthError) return 3 /* AUTH */;
268
+ if (err instanceof EnginiNotFoundError) return 4 /* NOT_FOUND */;
269
+ if (err instanceof EnginiValidationError) return 5 /* VALIDATION */;
270
+ return 1 /* GENERIC */;
271
+ }
272
+ async function apiErrors(fn) {
273
+ try {
274
+ return await fn();
275
+ } catch (err) {
276
+ if (err instanceof EnginiError) {
277
+ fail(exitForError(err), err.message);
278
+ }
279
+ throw err;
280
+ }
281
+ }
282
+
283
+ // src/tools/render.ts
284
+ function clean(value) {
285
+ return value ?? null;
286
+ }
287
+
288
+ // src/applications/get.ts
289
+ function detail(app) {
290
+ return {
291
+ slug: app.slug,
292
+ application_name: clean(app.applicationName),
293
+ description: app.description,
294
+ connection_requirement: app.connectionRequirement,
295
+ categories: app.categories,
296
+ tools_count: app.toolsCount,
297
+ triggers_count: app.triggersCount,
298
+ supports_object_selection: Boolean(clean(app.supportsObjectSelection)),
299
+ help_url: clean(app.helpUrl),
300
+ authentication_methods: clean(app.authenticationMethods)
301
+ };
302
+ }
303
+ async function getBody(slug) {
304
+ if (!slug) {
305
+ fail(2 /* USAGE */, "Missing required argument 'slug'.");
306
+ }
307
+ const app = await apiErrors(async () => {
308
+ const client = buildClient();
309
+ return client.applications.get(slug);
310
+ });
311
+ printOutput(detail(app));
312
+ }
313
+ function registerApplicationsGet(applications) {
314
+ const cmd = applications.command("get").description("Show full detail for one application.").argument("[slug]", "Application slug");
315
+ addUniversalOptions(cmd);
316
+ cmd.action(async (slug, opts, command) => {
317
+ await runCommand(command, opts, false, () => getBody(slug));
318
+ });
319
+ }
320
+
321
+ // src/applications/list.ts
322
+ function summarize(app) {
323
+ return {
324
+ slug: app.slug,
325
+ application_name: clean(app.applicationName),
326
+ description: app.description,
327
+ connection_requirement: app.connectionRequirement,
328
+ categories: app.categories,
329
+ tools_count: app.toolsCount,
330
+ triggers_count: app.triggersCount
331
+ };
332
+ }
333
+ function parseLimit(value) {
334
+ if (value === void 0) return void 0;
335
+ const limit = Number(value);
336
+ if (!Number.isInteger(limit) || limit < 0) {
337
+ fail(2 /* USAGE */, "--limit must be a non-negative integer.");
338
+ }
339
+ return limit;
340
+ }
341
+ async function listBody(opts) {
342
+ const limit = parseLimit(opts.limit);
343
+ const apps = await apiErrors(async () => {
344
+ const client = buildClient();
345
+ return client.applications.list({ search: opts.search, available: opts.available, limit });
346
+ });
347
+ printOutput(apps.map(summarize));
348
+ }
349
+ function registerApplicationsList(applications) {
350
+ const cmd = applications.command("list").description("Discover connector applications, optionally filtered.").option("--search <query>", "Free-text search across applications").option("--available", "Only applications you can currently use").option("--limit <n>", "Cap the number of applications returned");
351
+ addUniversalOptions(cmd);
352
+ cmd.action(async (opts, command) => {
353
+ await runCommand(command, opts, false, () => listBody(opts));
354
+ });
355
+ }
356
+
357
+ // src/applications/index.ts
358
+ function registerApplications(program) {
359
+ const applications = program.command("applications").description("Discover connector applications.");
360
+ registerApplicationsList(applications);
361
+ registerApplicationsGet(applications);
362
+ }
363
+
364
+ // src/connect.ts
365
+ function connectionsUrl(config) {
366
+ return `${config.identity_url.replace(/\/+$/, "")}/connections#integrations`;
367
+ }
368
+ function connectBody() {
369
+ const url = connectionsUrl(loadConfig());
370
+ openBrowser(url);
371
+ printOutput({ url });
372
+ }
373
+ function registerConnect(program) {
374
+ const cmd = program.command("connect").description("Open the Engini connections page in your browser.");
375
+ cmd.addHelpText(
376
+ "after",
377
+ "\nExamples:\n engini connect\n engini connect --json | jq -r '.url'"
378
+ );
379
+ addUniversalOptions(cmd);
380
+ cmd.action(async (opts, command) => {
381
+ await runCommand(command, opts, false, () => connectBody());
382
+ });
383
+ }
384
+
385
+ // src/connections/get.ts
386
+ function detail2(c) {
387
+ return {
388
+ connection_id: c.connectionId,
389
+ connection_name: c.connectionName,
390
+ application_slug: c.applicationSlug,
391
+ application_name: clean(c.applicationName),
392
+ description: clean(c.description),
393
+ is_public: c.isPublic,
394
+ authentication_type: clean(c.authenticationType),
395
+ is_alive: clean(c.isAlive),
396
+ connection_error: clean(c.connectionError),
397
+ use_select_db_objects: clean(c.useSelectDBObjects),
398
+ created_date: c.createdDate,
399
+ updated_date: clean(c.updatedDate)
400
+ };
401
+ }
402
+ function parseId(value) {
403
+ if (!value) {
404
+ fail(2 /* USAGE */, "Missing required argument 'connection_id'.");
405
+ }
406
+ const id = Number(value);
407
+ if (!Number.isInteger(id)) {
408
+ fail(2 /* USAGE */, "connection_id must be an integer.");
409
+ }
410
+ return id;
411
+ }
412
+ async function getBody2(connectionId) {
413
+ const id = parseId(connectionId);
414
+ const connection = await apiErrors(async () => {
415
+ const client = buildClient();
416
+ return client.connections.get(id);
417
+ });
418
+ printOutput(detail2(connection));
419
+ }
420
+ function registerConnectionsGet(connections) {
421
+ const cmd = connections.command("get").description("Show full detail for one connection.").argument("[connection_id]", "Connection id");
422
+ cmd.addHelpText("after", "\nExamples:\n engini connections get 42 --json");
423
+ addUniversalOptions(cmd);
424
+ cmd.action(async (id, opts, command) => {
425
+ await runCommand(command, opts, false, () => getBody2(id));
426
+ });
427
+ }
428
+
429
+ // src/connections/list.ts
430
+ function summarize2(c) {
431
+ return {
432
+ connection_id: c.connectionId,
433
+ connection_name: c.connectionName,
434
+ application_slug: c.applicationSlug,
435
+ application_name: clean(c.applicationName),
436
+ description: clean(c.description),
437
+ is_public: c.isPublic,
438
+ created_date: c.createdDate
439
+ };
440
+ }
441
+ async function listBody2(opts) {
442
+ const conns = await apiErrors(async () => {
443
+ const client = buildClient();
444
+ return client.connections.list(opts.application);
445
+ });
446
+ printOutput(conns.map(summarize2));
447
+ }
448
+ function registerConnectionsList(connections) {
449
+ const cmd = connections.command("list").description("List your connections, optionally filtered by application.").option("--application <slug>", "Filter by application slug");
450
+ cmd.addHelpText(
451
+ "after",
452
+ "\nExamples:\n engini connections list --json\n engini connections list --application monday\n engini connections list | jq -r '.[].connection_id'"
453
+ );
454
+ addUniversalOptions(cmd);
455
+ cmd.action(async (opts, command) => {
456
+ await runCommand(command, opts, false, () => listBody2(opts));
457
+ });
458
+ }
459
+
460
+ // src/connections/index.ts
461
+ function registerConnections(program) {
462
+ const connections = program.command("connections").description("List, inspect, and remove connections.");
463
+ registerConnectionsList(connections);
464
+ registerConnectionsGet(connections);
465
+ const del = connections.command("delete").description("Remove a connection.").argument("[connection_id]", "Connection id");
466
+ addUniversalOptions(del, { mutating: true });
467
+ del.action(async (_id, opts, command) => {
468
+ await runCommand(command, opts, true, () => notImplemented("connections delete"));
469
+ });
470
+ }
471
+
472
+ // src/help.ts
473
+ import { Help } from "commander";
474
+ var REPO_URL = "https://github.com/engini/engini-sdk";
475
+ var KEYS_URL = "https://app.engini.io/users";
476
+ var EXIT_LABELS = {
477
+ [0 /* OK */]: "success",
478
+ [1 /* GENERIC */]: "general error",
479
+ [2 /* USAGE */]: "usage error (bad flags/args)",
480
+ [3 /* AUTH */]: "authentication error",
481
+ [4 /* NOT_FOUND */]: "resource not found",
482
+ [5 /* VALIDATION */]: "validation error",
483
+ [124 /* TIMEOUT */]: "timeout"
484
+ };
485
+ function exitCodeLines() {
486
+ const codes = Object.values(Exit).filter((v) => typeof v === "number").sort((a, b) => a - b);
487
+ return codes.map((code) => ` ${String(code).padStart(3)} ${EXIT_LABELS[code] ?? "error"}`).join("\n");
488
+ }
489
+ function formatRootHelp() {
490
+ return `Engini CLI \u2014 run tools across your connected apps, from the terminal or an agent.
491
+
492
+ Discover tools with \`tools list\`, inspect one with \`tools get\`, then run it with
493
+ \`tools call\`. Output is machine-first: human-readable on a terminal, JSON when piped
494
+ (or with --json), with stable exit codes \u2014 so it composes in shell pipelines and agents.
495
+ Tip: \`tools call --dry-run\` validates inputs and previews the request without executing.
496
+
497
+ USAGE
498
+ engini <command> [options]
499
+ engini <command> --help
500
+
501
+ CORE COMMANDS
502
+ tools list [--application <slug>] [--toolset <id>] [--limit <n>]
503
+ Discover available tools (one concise summary per tool).
504
+ tools get <tool_id>
505
+ Full input/output schema + capability flags for one tool.
506
+ tools call <tool_id> --args <json|@file|-> [--connection <id>] [--raw] [--llm <vendor>]
507
+ Execute a tool against a connection. Validate first with --dry-run.
508
+ applications list [--search <q>] [--available] [--limit <n>]
509
+ Browse connector apps (slug, categories, tool counts).
510
+ applications get <slug>
511
+ Full detail for one app, including how to connect it.
512
+
513
+ Typical flow: login \u2192 applications list \u2192 tools list \u2192 tools call
514
+
515
+ ACCOUNT
516
+ login Store an opaque Engini API key (eng_\u2026): --api-key, or interactive on a TTY.
517
+ logout Clear the stored credentials.
518
+ whoami Show the authenticated user/company. (coming soon)
519
+
520
+ CONNECTIONS
521
+ connections list List connections. (coming soon)
522
+ connections get <id> Inspect a connection. (coming soon)
523
+ connections delete <id> Remove a connection. (coming soon)
524
+ connect <app> [--token] Connect a third-party app. (coming soon)
525
+
526
+ OUTPUT & EXIT CODES
527
+ Output adapts to context: human-readable on a TTY, compact JSON when piped, pretty
528
+ JSON with --json. Universal flags on every command:
529
+ --json Pretty-print JSON
530
+ --quiet Suppress non-essential output
531
+ --schema Print the command's machine-readable arg schema (great for agents)
532
+ --dry-run Preview a mutating command without executing it
533
+ Exit codes:
534
+ ${exitCodeLines()}
535
+
536
+ FILES & ENVIRONMENT
537
+ Config: $XDG_CONFIG_HOME/engini/config.toml (Windows: %APPDATA%\\engini\\config.toml)
538
+ Written 0600; stores api_url / identity_url / api_key / auth_kind.
539
+ Re-run \`engini login\` to change it.
540
+ Env: ENGINI_API_KEY (preferred) or ENGINI_API_TOKEN, plus ENGINI_COMPANY_TOKEN.
541
+ Resolution order: flags > environment > config.
542
+
543
+ EXAMPLES
544
+ # Authenticate (or set ENGINI_API_KEY)
545
+ engini login --api-key eng_\u2026
546
+
547
+ # Discover apps and tools; pipe JSON to jq
548
+ engini applications list --available --limit 10
549
+ engini tools list --application monday --limit 5
550
+ engini tools list | jq -r '.[].tool_slug'
551
+
552
+ # Inspect a tool's input schema
553
+ engini tools get monday_create_item --json
554
+
555
+ # Execute \u2014 literal JSON, @file, or - for stdin; preview first
556
+ engini tools call monday_create_item --args '{}' --dry-run
557
+ engini tools call monday_create_item --args @item.json --connection 3
558
+ echo '{"name":"x"}' | engini tools call monday_create_item --args -
559
+
560
+ # Provider-shaped result for an agent loop
561
+ engini tools call monday_create_item --args '{}' --llm openai --tool-call-id call_1
562
+
563
+ # Machine-readable arg schema (for agents)
564
+ engini tools call --schema
565
+
566
+ LEARN MORE
567
+ Use \`engini <command> --help\` for details on any command.
568
+ Source & docs: ${REPO_URL}
569
+ Get an API key: ${KEYS_URL}
570
+ `;
571
+ }
572
+ var EXAMPLES = {
573
+ login: `Examples:
574
+ engini login --api-key eng_\u2026 # store a key non-interactively
575
+ engini login --api-url https://staging.engini.io # point at another environment
576
+ engini login --api-key eng_\u2026 --dry-run # preview without writing`,
577
+ "tools list": `Examples:
578
+ engini tools list --application monday --limit 5
579
+ engini tools list | jq -r '.[].tool_slug'
580
+ engini tools list --toolset <toolset_id> --json`,
581
+ "tools get": `Examples:
582
+ engini tools get monday_create_item --json`,
583
+ "tools call": `Examples:
584
+ engini tools call monday_create_item --args '{}' --dry-run
585
+ engini tools call monday_create_item --args @item.json --connection 3
586
+ echo '{"name":"x"}' | engini tools call monday_create_item --args -
587
+ engini tools call monday_create_item --args '{}' --llm openai --tool-call-id call_1`,
588
+ "applications list": `Examples:
589
+ engini applications list --available --limit 10
590
+ engini applications list --search crm --json
591
+ engini applications list | jq -r '.[].slug'`,
592
+ "applications get": `Examples:
593
+ engini applications get monday --json`
594
+ };
595
+ function addExamples(cmd, text) {
596
+ if (cmd && text) cmd.addHelpText("after", `
597
+ ${text}`);
598
+ }
599
+ var baseFormatHelp = Help.prototype.formatHelp;
600
+ function installHelp(program) {
601
+ program.configureHelp({
602
+ sortSubcommands: false,
603
+ formatHelp(cmd, helper) {
604
+ return cmd === program ? formatRootHelp() : baseFormatHelp.call(helper, cmd, helper);
605
+ }
606
+ });
607
+ const find = (name) => program.commands.find((c) => c.name() === name);
608
+ addExamples(find("login"), EXAMPLES.login);
609
+ const tools = find("tools");
610
+ if (tools) {
611
+ const sub = (name) => tools.commands.find((c) => c.name() === name);
612
+ addExamples(sub("list"), EXAMPLES["tools list"]);
613
+ addExamples(sub("get"), EXAMPLES["tools get"]);
614
+ addExamples(sub("call"), EXAMPLES["tools call"]);
615
+ }
616
+ const applications = find("applications");
617
+ if (applications) {
618
+ const sub = (name) => applications.commands.find((c) => c.name() === name);
619
+ addExamples(sub("list"), EXAMPLES["applications list"]);
620
+ addExamples(sub("get"), EXAMPLES["applications get"]);
621
+ }
622
+ }
623
+
624
+ // src/login.ts
625
+ function keysUrl(config) {
626
+ return `${config.identity_url.replace(/\/+$/, "")}/users`;
627
+ }
628
+ async function loginBody(opts) {
629
+ const config = loadConfig();
630
+ const hadCredentials = Boolean(config.api_key || config.api_token);
631
+ if (opts.apiUrl) config.api_url = opts.apiUrl;
632
+ if (opts.identityUrl) config.identity_url = opts.identityUrl;
633
+ let apiKey = opts.apiKey;
634
+ if (!apiKey) {
635
+ if (!isTty()) {
636
+ fail(2 /* USAGE */, "Provide --api-key when running non-interactively.");
637
+ }
638
+ if (!await confirm("Do you already have an Engini API key?")) {
639
+ const url = keysUrl(config);
640
+ console.log(`Opening ${url} \u2014 create a key there, then paste it below.`);
641
+ openBrowser(url);
642
+ }
643
+ apiKey = await promptHidden("Paste your API key (eng_\u2026)");
644
+ }
645
+ config.api_key = apiKey;
646
+ config.auth_kind = "api-key";
647
+ const summary2 = {
648
+ auth_kind: "api-key",
649
+ credential: maskSecret(apiKey),
650
+ api_url: config.api_url
651
+ };
652
+ if (dryRun()) {
653
+ printOutput({ would_store: summary2 });
654
+ return;
655
+ }
656
+ if (hadCredentials) {
657
+ await confirmOrFail("Credentials already exist. Overwrite?", { force: Boolean(opts.force) });
658
+ }
659
+ saveConfig(config);
660
+ printOutput({ stored: summary2 });
661
+ }
662
+ function registerLogin(program) {
663
+ const cmd = program.command("login").description("Store an opaque Engini API key.").option("--api-key <key>", "Opaque Engini key (eng_\u2026)").option("--api-url <url>", "API base URL to persist (e.g. a staging host)").option("--identity-url <url>", "Dashboard base URL to persist (hosts the keys page)").option("--force", "Overwrite existing credentials without confirming");
664
+ addUniversalOptions(cmd, { mutating: true });
665
+ cmd.action(async (opts, command) => {
666
+ await runCommand(command, opts, true, () => loginBody(opts));
667
+ });
668
+ }
669
+
670
+ // src/logout.ts
671
+ function logoutBody() {
672
+ const config = loadConfig();
673
+ if (!(config.api_key || config.api_token)) {
674
+ printOutput({ logged_out: false, noop: true });
675
+ return;
676
+ }
677
+ if (dryRun()) {
678
+ printOutput({ would_logout: true });
679
+ return;
680
+ }
681
+ config.api_key = void 0;
682
+ config.api_token = void 0;
683
+ config.company_token = void 0;
684
+ config.auth_kind = void 0;
685
+ saveConfig(config);
686
+ printOutput({ logged_out: true });
687
+ }
688
+ function registerLogout(program) {
689
+ const cmd = program.command("logout").description("Clear the stored credentials.");
690
+ addUniversalOptions(cmd, { mutating: true });
691
+ cmd.action(async (opts, command) => {
692
+ await runCommand(command, opts, true, logoutBody);
693
+ });
694
+ }
695
+
696
+ // src/tools/call.ts
697
+ import { readFileSync as readFileSync2 } from "fs";
698
+ import {
699
+ AnthropicProvider,
700
+ OpenAIProvider
701
+ } from "@engini/sdk";
702
+ function loadArgs(spec) {
703
+ let text;
704
+ if (spec === "-") {
705
+ text = readFileSync2(0, "utf8");
706
+ } else if (spec.startsWith("@")) {
707
+ try {
708
+ text = readFileSync2(spec.slice(1), "utf8");
709
+ } catch (err) {
710
+ return fail(2 /* USAGE */, `Cannot read ${spec.slice(1)}: ${err.message}`);
711
+ }
712
+ } else {
713
+ text = spec;
714
+ }
715
+ let data;
716
+ try {
717
+ data = JSON.parse(text);
718
+ } catch (err) {
719
+ return fail(2 /* USAGE */, `--args is not valid JSON: ${err.message}`);
720
+ }
721
+ if (data === null || typeof data !== "object" || Array.isArray(data)) {
722
+ return fail(2 /* USAGE */, "--args must be a JSON object.");
723
+ }
724
+ return data;
725
+ }
726
+ function parseConnection(value) {
727
+ if (value === void 0) return void 0;
728
+ const id = Number(value);
729
+ if (!Number.isInteger(id)) {
730
+ return fail(2 /* USAGE */, "--connection must be an integer connection id.");
731
+ }
732
+ return id;
733
+ }
734
+ function providerFor(vendor) {
735
+ if (vendor === "openai") return new OpenAIProvider();
736
+ if (vendor === "anthropic") return new AnthropicProvider();
737
+ return fail(2 /* USAGE */, `Unknown --llm vendor '${vendor}'; use openai|anthropic.`);
738
+ }
739
+ function renderResult(result, opts) {
740
+ if (opts.raw) return result.output;
741
+ if (opts.llm) {
742
+ const provider = providerFor(opts.llm);
743
+ const call = { id: opts.toolCallId ?? opts.toolId, name: opts.toolId, arguments: {} };
744
+ return provider.formatToolResult(call, { output: result.output });
745
+ }
746
+ return {
747
+ output: result.output,
748
+ history_id: result.historyId,
749
+ execution_info: result.executionInfo
750
+ };
751
+ }
752
+ async function callBody(toolId, opts) {
753
+ if (!toolId) {
754
+ fail(2 /* USAGE */, "Missing required argument 'tool_id'.");
755
+ }
756
+ if (opts.args === void 0) {
757
+ fail(2 /* USAGE */, "Missing required option --args.");
758
+ }
759
+ if (opts.raw && opts.llm) {
760
+ fail(2 /* USAGE */, "Pass only one of --raw / --llm.");
761
+ }
762
+ const args = loadArgs(opts.args);
763
+ const connection = parseConnection(opts.connection);
764
+ if (dryRun()) {
765
+ printOutput({
766
+ would_call: {
767
+ tool_slug: toolId,
768
+ arguments: args,
769
+ connection_id: connection ?? null,
770
+ toolset_id: opts.toolset ?? null
771
+ }
772
+ });
773
+ return;
774
+ }
775
+ const result = await apiErrors(async () => {
776
+ const client = buildClient();
777
+ return client.tools.execute(toolId, args, {
778
+ connectionId: connection,
779
+ toolsetId: opts.toolset
780
+ });
781
+ });
782
+ printOutput(
783
+ renderResult(result, {
784
+ raw: opts.raw,
785
+ llm: opts.llm,
786
+ toolId,
787
+ toolCallId: opts.toolCallId
788
+ })
789
+ );
790
+ }
791
+ function registerToolsCall(tools) {
792
+ const cmd = tools.command("call").description("Execute a tool against a connection.").argument("[tool_id]", "Tool slug").option("--args <args>", "JSON object, @file.json, or - for stdin").option("--connection <id>", "Connection id to run against").option("--toolset <id>", "Toolset id to resolve the connection").option("--raw", "Emit the tool output verbatim (no envelope)").option("--llm <vendor>", "Provider-shaped result: openai|anthropic").option("--tool-call-id <id>", "Correlation id for --llm output");
793
+ addUniversalOptions(cmd, { mutating: true });
794
+ cmd.action(async (toolId, opts, command) => {
795
+ await runCommand(command, opts, true, () => callBody(toolId, opts));
796
+ });
797
+ }
798
+
799
+ // src/tools/get.ts
800
+ function detail3(schema) {
801
+ return {
802
+ tool_slug: schema.toolSlug,
803
+ tool_name: clean(schema.toolName),
804
+ application_slug: schema.applicationSlug,
805
+ application_name: clean(schema.applicationName),
806
+ category: schema.category,
807
+ version: clean(schema.version),
808
+ is_deprecated: Boolean(schema.isDeprecated),
809
+ description: clean(schema.description),
810
+ input_schema: clean(schema.inputSchema),
811
+ output_schema: clean(schema.outputSchema),
812
+ supports_filters: Boolean(schema.supportsFilters),
813
+ supports_sort: Boolean(schema.supportsSort),
814
+ supports_top_offset: Boolean(schema.supportsTopOffset),
815
+ max_filters: clean(schema.maxFilters),
816
+ max_sorts: clean(schema.maxSorts)
817
+ };
818
+ }
819
+ async function getBody3(toolId) {
820
+ if (!toolId) {
821
+ fail(2 /* USAGE */, "Missing required argument 'tool_id'.");
822
+ }
823
+ const schema = await apiErrors(async () => {
824
+ const client = buildClient();
825
+ return client.tools.getOne(toolId);
826
+ });
827
+ printOutput(detail3(schema));
828
+ }
829
+ function registerToolsGet(tools) {
830
+ const cmd = tools.command("get").description("Show full canonical detail for one tool.").argument("[tool_id]", "Tool slug");
831
+ addUniversalOptions(cmd);
832
+ cmd.action(async (toolId, opts, command) => {
833
+ await runCommand(command, opts, false, () => getBody3(toolId));
834
+ });
835
+ }
836
+
837
+ // src/tools/list.ts
838
+ function summarize3(schema) {
839
+ return {
840
+ tool_slug: schema.toolSlug,
841
+ tool_name: clean(schema.toolName),
842
+ application_slug: schema.applicationSlug,
843
+ category: schema.category,
844
+ is_deprecated: Boolean(schema.isDeprecated),
845
+ description: clean(schema.description)
846
+ };
847
+ }
848
+ function parseLimit2(value) {
849
+ if (value === void 0) return void 0;
850
+ const limit = Number(value);
851
+ if (!Number.isInteger(limit) || limit < 0) {
852
+ fail(2 /* USAGE */, "--limit must be a non-negative integer.");
853
+ }
854
+ return limit;
855
+ }
856
+ async function listBody3(opts) {
857
+ if (opts.application && opts.toolset) {
858
+ fail(2 /* USAGE */, "Pass only one of --application / --toolset.");
859
+ }
860
+ const limit = parseLimit2(opts.limit);
861
+ const schemas = await apiErrors(async () => {
862
+ const client = buildClient();
863
+ if (opts.toolset !== void 0) {
864
+ const toolset = await client.toolset({ toolsetId: opts.toolset });
865
+ const tools = await toolset.tools({ format: "canonical" });
866
+ return limit !== void 0 ? tools.slice(0, limit) : tools;
867
+ }
868
+ return client.tools.get({
869
+ applications: opts.application ? [opts.application] : void 0,
870
+ limit
871
+ });
872
+ });
873
+ printOutput(schemas.map(summarize3));
874
+ }
875
+ function registerToolsList(tools) {
876
+ const cmd = tools.command("list").description("List available tools, optionally filtered.").option("--application <slug>", "Filter by application slug (e.g. monday)").option("--toolset <id>", "List the tools of a server toolset (by id)").option("--limit <n>", "Cap the number of tools returned");
877
+ addUniversalOptions(cmd);
878
+ cmd.action(async (opts, command) => {
879
+ await runCommand(command, opts, false, () => listBody3(opts));
880
+ });
881
+ }
882
+
883
+ // src/tools/index.ts
884
+ function registerTools(program) {
885
+ const tools = program.command("tools").description("Discover and execute tools.");
886
+ registerToolsList(tools);
887
+ registerToolsGet(tools);
888
+ registerToolsCall(tools);
889
+ }
890
+
891
+ // src/whoami.ts
892
+ function summary(me) {
893
+ return {
894
+ full_name: clean(me.fullName),
895
+ email: clean(me.email),
896
+ current_company: clean(me.currentCompany),
897
+ role: clean(me.role),
898
+ user_type: me.userType
899
+ };
900
+ }
901
+ async function whoamiBody() {
902
+ const me = await apiErrors(async () => {
903
+ const client = buildClient();
904
+ return client.auth.whoami();
905
+ });
906
+ printOutput(summary(me));
907
+ }
908
+ function registerWhoami(program) {
909
+ const cmd = program.command("whoami").description("Report the authenticated user/company.");
910
+ cmd.addHelpText("after", "\nExamples:\n engini whoami\n engini whoami --json | jq -r '.email'");
911
+ addUniversalOptions(cmd);
912
+ cmd.action(async (opts, command) => {
913
+ await runCommand(command, opts, false, () => whoamiBody());
914
+ });
915
+ }
916
+
917
+ // src/version.ts
918
+ var VERSION = true ? "0.4.0" : "0.0.0";
919
+
920
+ // src/main.ts
921
+ function buildProgram() {
922
+ const program = new Command();
923
+ program.name("engini").description("Engini CLI.").version(VERSION, "--version", "Print the engini SDK/CLI version and exit").showHelpAfterError();
924
+ registerLogin(program);
925
+ registerLogout(program);
926
+ registerWhoami(program);
927
+ registerConnect(program);
928
+ registerTools(program);
929
+ registerApplications(program);
930
+ registerConnections(program);
931
+ installHelp(program);
932
+ return program;
933
+ }
934
+
935
+ // src/index.ts
936
+ function applyExitOverride(command) {
937
+ command.exitOverride();
938
+ for (const sub of command.commands) applyExitOverride(sub);
939
+ }
940
+ async function main(argv = process.argv.slice(2)) {
941
+ const program = buildProgram();
942
+ applyExitOverride(program);
943
+ try {
944
+ if (argv.length === 0) {
945
+ program.outputHelp();
946
+ process.exit(0);
947
+ }
948
+ await program.parseAsync(argv, { from: "user" });
949
+ } catch (err) {
950
+ if (err instanceof CliError) {
951
+ process.exit(err.code);
952
+ }
953
+ if (err && typeof err === "object" && "exitCode" in err) {
954
+ process.exit(err.exitCode ?? 1);
955
+ }
956
+ console.error(err instanceof Error ? err.message : String(err));
957
+ process.exit(1);
958
+ }
959
+ }
960
+ main();
961
+ export {
962
+ main
963
+ };
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@engini/cli",
3
+ "version": "0.4.0",
4
+ "description": "Engini CLI — machine-first command line over the Engini Public API",
5
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "bin": {
8
+ "engini": "./dist/cli.js"
9
+ },
10
+ "files": [
11
+ "dist"
12
+ ],
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://github.com/engini/engini-sdk",
16
+ "directory": "ts/packages/cli"
17
+ },
18
+ "scripts": {
19
+ "typecheck": "tsc --noEmit",
20
+ "build": "tsup",
21
+ "test": "vitest run"
22
+ },
23
+ "dependencies": {
24
+ "@engini/sdk": "^0.3.0",
25
+ "commander": "^12.1.0",
26
+ "smol-toml": "^1.3.0"
27
+ },
28
+ "devDependencies": {
29
+ "@types/node": "^25.9.2",
30
+ "tsup": "^8.3.0",
31
+ "typescript": "^5.5.0",
32
+ "vitest": "^2.1.0"
33
+ }
34
+ }