@engini/cli 0.7.0 → 0.8.1

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 +34 -1
  2. package/dist/cli.js +620 -18
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -29,12 +29,45 @@ engini tools result <handle> --select items.email # drill into a large result
29
29
  engini login | logout | whoami # auth
30
30
  engini tools list | get | call | result # discover, execute & drill into results
31
31
  engini applications list | get # browse connector apps
32
+ engini connect [<app>] # create a connection (interactive / agent-resumable)
32
33
  engini connections list | get # inspect connections
33
- engini connect # open the connections page in your browser
34
+ engini connections create | check | refresh | objects | select-objects # creation-flow primitives
35
+ engini connections sign-in-url | oauth-complete # OAuth2 start / finish primitives
34
36
  ```
35
37
 
36
38
  Run `engini <command> --help` for details and examples on any command.
37
39
 
40
+ `connect <app>` discovers the app's authentication methods, collects credentials
41
+ (or runs the OAuth2 sign-in), creates the connection, checks it, refreshes its
42
+ objects, and — when the app supports it — lets you pick which objects to sync.
43
+ On a TTY it prompts and opens the browser inline. Async jobs poll up to
44
+ `--timeout` (`--no-wait` returns early; a timeout exits `124`).
45
+
46
+ ### Agent recipe (piped / non-TTY)
47
+
48
+ `connect` never blocks for an agent: at each gate it prints a self-describing
49
+ `{ "need": …, "resume": "<exact next command>" }` and exits `5`. The agent asks
50
+ the user for the value and runs the `resume` command:
51
+
52
+ ```bash
53
+ # direct-credential (e.g. monday)
54
+ engini connect monday --json # → {need:"fields", resume:"engini connect monday --auth 0 --field ApiKey=<value>"}
55
+ engini connect monday --auth 0 --field ApiKey=<key> # creates → checks → refreshes
56
+
57
+ # OAuth2 (e.g. outlook) — never opens a browser for the agent
58
+ engini connect outlook --json # → {need:"oauth", sign_in_url, state, resume:"engini connect outlook --oauth-state <state>"}
59
+ # show sign_in_url to the user; after they sign in:
60
+ engini connect outlook --oauth-state <state> # polls token → creates → checks → refreshes
61
+
62
+ # object selection (apps that support it) — resume never re-creates
63
+ engini connect <app> --json # → {need:"objects", connection_id, objects, resume:"engini connect <app> --connection <id> --object <id>"}
64
+ engini connect <app> --connection <id> --object 5 --object 9
65
+ ```
66
+
67
+ The same steps are available as standalone primitives: `connections sign-in-url`
68
+ / `oauth-complete` (OAuth) and `connections create` / `check` / `refresh` /
69
+ `objects` / `select-objects`.
70
+
38
71
  ## Output & exit codes
39
72
 
40
73
  Output adapts to context: human-readable on a TTY, **compact JSON when piped**, pretty JSON
package/dist/cli.js CHANGED
@@ -26,6 +26,16 @@ async function confirm(question) {
26
26
  rl.close();
27
27
  }
28
28
  }
29
+ async function promptText(label, fallback = "") {
30
+ const suffix = fallback ? ` [${fallback}]` : "";
31
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
32
+ try {
33
+ const answer = (await ask(rl, `${label}${suffix}: `)).trim();
34
+ return answer || fallback;
35
+ } finally {
36
+ rl.close();
37
+ }
38
+ }
29
39
  async function promptHidden(label) {
30
40
  const output = process.stdout;
31
41
  const rl = createInterface({ input: process.stdin, output, terminal: true });
@@ -107,6 +117,9 @@ function printOutput(obj) {
107
117
  pretty(obj);
108
118
  }
109
119
  }
120
+ function progress(message) {
121
+ if (isTty() && !context.quiet) console.error(message);
122
+ }
110
123
  function fail(code, message, hint2) {
111
124
  if (isTty()) {
112
125
  console.error(`Error: ${message}`);
@@ -199,6 +212,7 @@ import {
199
212
  EnginiAuthError,
200
213
  EnginiError,
201
214
  EnginiNotFoundError,
215
+ EnginiTimeoutError,
202
216
  EnginiValidationError
203
217
  } from "@engini/sdk";
204
218
 
@@ -267,6 +281,7 @@ function exitForError(err) {
267
281
  if (err instanceof EnginiAuthError) return 3 /* AUTH */;
268
282
  if (err instanceof EnginiNotFoundError) return 4 /* NOT_FOUND */;
269
283
  if (err instanceof EnginiValidationError) return 5 /* VALIDATION */;
284
+ if (err instanceof EnginiTimeoutError) return 124 /* TIMEOUT */;
270
285
  return 1 /* GENERIC */;
271
286
  }
272
287
  async function apiErrors(fn) {
@@ -361,24 +376,414 @@ function registerApplications(program) {
361
376
  registerApplicationsGet(applications);
362
377
  }
363
378
 
379
+ // src/connections/shared.ts
380
+ import { refreshFailed } from "@engini/sdk";
381
+ var OAUTH_DONE = /* @__PURE__ */ new Set(["completed", "complete", "success", "succeeded"]);
382
+ var OAUTH_FAILED = /* @__PURE__ */ new Set(["failed", "error", "cancelled", "canceled", "denied"]);
383
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
384
+ function collect(value, previous = []) {
385
+ return [...previous, value];
386
+ }
387
+ function parseId(value) {
388
+ if (!value) fail(2 /* USAGE */, "Missing required argument 'connection_id'.");
389
+ const id = Number(value);
390
+ if (!Number.isInteger(id)) fail(2 /* USAGE */, "connection_id must be an integer.");
391
+ return id;
392
+ }
393
+ function parseFields(specs) {
394
+ const out = {};
395
+ for (const spec of specs ?? []) {
396
+ const eq = spec.indexOf("=");
397
+ if (eq <= 0) {
398
+ fail(2 /* USAGE */, `--field must be key=value, got '${spec}'.`);
399
+ }
400
+ out[spec.slice(0, eq)] = spec.slice(eq + 1);
401
+ }
402
+ return out;
403
+ }
404
+ function need(payload) {
405
+ printOutput(payload);
406
+ throw new CliError(5 /* VALIDATION */);
407
+ }
408
+ function checkAlive(result) {
409
+ if (typeof result === "boolean") return result;
410
+ if (result && typeof result === "object") {
411
+ const record = result;
412
+ for (const key of ["isAlive", "is_alive", "alive", "isHealthy", "healthy", "success"]) {
413
+ if (key in record) return Boolean(record[key]);
414
+ }
415
+ }
416
+ return null;
417
+ }
418
+ async function pollRefresh(client, connectionId, opts) {
419
+ if (!opts.wait) return "pending";
420
+ progress(
421
+ `Refreshing objects \u2014 this can take a moment (up to ${Math.round(opts.timeout)}s, Ctrl-C to abort)\u2026`
422
+ );
423
+ const status = await client.connections.waitForRefresh(connectionId, {
424
+ timeout: opts.timeout,
425
+ interval: opts.interval
426
+ });
427
+ if (refreshFailed(status)) {
428
+ const error = clean(status.error);
429
+ fail(1 /* GENERIC */, `Refresh failed: ${error ?? "the refresh job reported failure"}`);
430
+ }
431
+ return "completed";
432
+ }
433
+ async function pollAccessToken(client, state, opts) {
434
+ progress(
435
+ `Waiting for you to finish signing in (up to ${Math.round(opts.timeout)}s, Ctrl-C to abort)\u2026`
436
+ );
437
+ const deadline = Date.now() + opts.timeout * 1e3;
438
+ for (; ; ) {
439
+ const resp = await client.connections.getAccessToken(state);
440
+ const status = (resp.status ?? "").toLowerCase();
441
+ if (OAUTH_DONE.has(status)) return resp;
442
+ if (OAUTH_FAILED.has(status)) {
443
+ fail(1 /* GENERIC */, clean(resp.error_message) ?? "OAuth sign-in failed.");
444
+ }
445
+ if (Date.now() >= deadline) {
446
+ fail(124 /* TIMEOUT */, "OAuth sign-in did not complete in time.");
447
+ }
448
+ await sleep(opts.interval * 1e3);
449
+ }
450
+ }
451
+ function oauthFields(token) {
452
+ const fields = {};
453
+ for (const [key, value] of Object.entries(token.connectionData ?? {})) {
454
+ if (value === null || value === void 0) continue;
455
+ fields[key] = typeof value === "string" ? value : JSON.stringify(value);
456
+ }
457
+ return fields;
458
+ }
459
+
364
460
  // src/connect.ts
365
461
  function connectionsUrl(config) {
366
462
  return `${config.identity_url.replace(/\/+$/, "")}/connections#integrations`;
367
463
  }
368
- function connectBody() {
369
- const url = connectionsUrl(loadConfig());
370
- openBrowser(url);
371
- printOutput({ url });
464
+ async function connectBody(application, opts) {
465
+ if (!application && opts.connection === void 0) {
466
+ const url = connectionsUrl(loadConfig());
467
+ openBrowser(url);
468
+ printOutput({ url });
469
+ return;
470
+ }
471
+ const timing = {
472
+ wait: opts.wait !== false,
473
+ timeout: Number(opts.timeout ?? 300),
474
+ interval: Number(opts.pollInterval ?? 2)
475
+ };
476
+ const noObjects = opts.objects === false;
477
+ await apiErrors(async () => {
478
+ const client = buildClient();
479
+ if (opts.connection !== void 0) {
480
+ const connectionId2 = parseId(opts.connection);
481
+ const selected = await selectObjectStep(client, application, connectionId2, opts.object, {
482
+ ...timing,
483
+ noObjects,
484
+ supported: true
485
+ });
486
+ printOutput({ connection_id: connectionId2, objects_selected: selected });
487
+ return;
488
+ }
489
+ if (!application) fail(2 /* USAGE */, "Missing required argument 'application'.");
490
+ const detail4 = await client.applications.get(application);
491
+ const method = await chooseAuth(detail4.authenticationMethods ?? [], opts.auth, application);
492
+ if (dryRun()) {
493
+ printOutput({
494
+ would_connect: {
495
+ application,
496
+ authentication_id: method.authenticationId,
497
+ oauth: Boolean(method.requiresOAuthSignIn)
498
+ }
499
+ });
500
+ return;
501
+ }
502
+ const name = await resolveName(opts.name, application);
503
+ const fields = method.requiresOAuthSignIn ? await oauthFieldsFor(client, application, method, opts.oauthState, timing) : await collectFields(method, application, opts.field);
504
+ progress(`Creating connection '${name}'\u2026`);
505
+ const created = await client.connections.create(
506
+ application,
507
+ name,
508
+ method.authenticationId,
509
+ fields
510
+ );
511
+ const connectionId = created.connectionId;
512
+ progress(`Checking connection ${connectionId}\u2026`);
513
+ const alive = checkAlive(await client.connections.check(connectionId));
514
+ if (alive === false) {
515
+ fail(1 /* GENERIC */, `Connection ${connectionId} failed its liveness check.`);
516
+ }
517
+ await client.connections.refresh(connectionId);
518
+ await pollRefresh(client, connectionId, timing);
519
+ const objectsSelected = await selectObjectStep(client, application, connectionId, opts.object, {
520
+ ...timing,
521
+ noObjects,
522
+ supported: supportsObjectSelection(detail4, created)
523
+ });
524
+ printOutput({
525
+ connection_id: connectionId,
526
+ is_alive: alive,
527
+ objects_selected: objectsSelected
528
+ });
529
+ });
530
+ }
531
+ function supportsObjectSelection(detail4, created) {
532
+ if (clean(detail4.supportsObjectSelection)) return true;
533
+ return Boolean(created && clean(created.useSelectDBObjects));
534
+ }
535
+ function parseObjectIds(specs) {
536
+ return (specs ?? []).map((value) => {
537
+ const n = Number(value);
538
+ if (!Number.isInteger(n)) fail(2 /* USAGE */, `--object must be an integer, got '${value}'.`);
539
+ return n;
540
+ });
541
+ }
542
+ async function chooseAuth(methods, auth, application) {
543
+ if (methods.length === 0) {
544
+ fail(1 /* GENERIC */, `Application '${application}' exposes no authentication methods.`);
545
+ }
546
+ const byId = new Map(methods.map((m) => [m.authenticationId, m]));
547
+ if (auth !== void 0) {
548
+ const id = Number(auth);
549
+ const chosen = byId.get(id);
550
+ if (!chosen) {
551
+ fail(
552
+ 2 /* USAGE */,
553
+ `No authentication method with id ${auth} for '${application}'.`,
554
+ `Run \`engini connect ${application} --json\` to list them.`
555
+ );
556
+ }
557
+ return chosen;
558
+ }
559
+ if (methods.length === 1) return methods[0];
560
+ if (isTty()) {
561
+ for (const m of methods) {
562
+ console.error(` ${m.authenticationId}: ${m.authenticationName} (${m.authenticationType})`);
563
+ }
564
+ const id = Number(await promptText("Choose an authentication method id"));
565
+ const chosen = byId.get(id);
566
+ if (!chosen) fail(2 /* USAGE */, `No authentication method with id ${id}.`);
567
+ return chosen;
568
+ }
569
+ return need({
570
+ need: "auth",
571
+ application,
572
+ methods: methods.map(methodSummary),
573
+ resume: `engini connect ${application} --auth <id>`
574
+ });
575
+ }
576
+ async function collectFields(method, application, field) {
577
+ const provided = parseFields(field);
578
+ const schema = method.connectionFields.filter((f) => !f.isHidden);
579
+ const required = schema.filter((f) => f.isRequired);
580
+ const missing = required.filter((f) => !(f.fieldName in provided));
581
+ if (missing.length === 0) return provided;
582
+ if (isTty()) {
583
+ for (const f of schema) {
584
+ if (f.fieldName in provided) continue;
585
+ const label = fieldLabel(f);
586
+ const value = f.isPassword ? await promptHidden(label) : await promptText(label, clean(f.defaultValue) ?? "");
587
+ if (value) provided[f.fieldName] = value;
588
+ }
589
+ return provided;
590
+ }
591
+ const fieldsFlags = required.map((f) => `--field ${f.fieldName}=<value>`).join(" ");
592
+ return need({
593
+ need: "fields",
594
+ application,
595
+ authentication_id: method.authenticationId,
596
+ fields: schema.map(fieldSummary),
597
+ resume: `engini connect ${application} --auth ${method.authenticationId} ${fieldsFlags}`
598
+ });
599
+ }
600
+ async function resolveName(name, application) {
601
+ if (name) return name;
602
+ const fallback = `${application} connection`;
603
+ if (isTty()) return promptText("Connection name", fallback);
604
+ return fallback;
605
+ }
606
+ async function selectObjectStep(client, application, connectionId, objectSpecs, opts) {
607
+ if (opts.noObjects || !opts.supported) return 0;
608
+ let ids = parseObjectIds(objectSpecs);
609
+ if (ids.length === 0) {
610
+ progress("Loading available objects\u2026");
611
+ const objs = await client.connections.objects(connectionId);
612
+ ids = await resolveObjects(objs, connectionId, application);
613
+ }
614
+ if (ids.length === 0) return 0;
615
+ await client.connections.selectObjects(connectionId, ids);
616
+ await pollRefresh(client, connectionId, opts);
617
+ return ids.length;
618
+ }
619
+ async function resolveObjects(objs, connectionId, application) {
620
+ if (objs.length === 0) return [];
621
+ if (isTty()) {
622
+ for (const o of objs) console.error(` ${o.objectId}: ${o.name} (${o.type})`);
623
+ const raw = await promptText("Object ids to select (comma/space separated, blank for none)");
624
+ return raw.split(/[\s,]+/).filter(Boolean).map(Number).filter(Number.isInteger);
625
+ }
626
+ const app = application ?? "<app>";
627
+ return need({
628
+ need: "objects",
629
+ application,
630
+ connection_id: connectionId,
631
+ objects: objs.map(objectSummary),
632
+ resume: `engini connect ${app} --connection ${connectionId} --object <id>`
633
+ });
634
+ }
635
+ async function oauthFieldsFor(client, application, method, oauthState, timing) {
636
+ if (oauthState) {
637
+ const token = await pollAccessToken(client, oauthState, timing);
638
+ return oauthFields(token);
639
+ }
640
+ const resp = await client.connections.getSignInUrl(application, method.authenticationId);
641
+ if (isTty() && timing.wait) {
642
+ openBrowser(resp.signInUrl);
643
+ progress(`Opened ${resp.signInUrl} \u2014 complete the sign-in in your browser.`);
644
+ const token = await pollAccessToken(client, resp.state, timing);
645
+ return oauthFields(token);
646
+ }
647
+ return need({
648
+ need: "oauth",
649
+ application,
650
+ authentication_id: method.authenticationId,
651
+ sign_in_url: resp.signInUrl,
652
+ state: resp.state,
653
+ resume: `engini connect ${application} --oauth-state ${resp.state}`
654
+ });
655
+ }
656
+ function fieldLabel(f) {
657
+ const label = clean(f.fieldDescription) ?? f.fieldName;
658
+ const placeholder = clean(f.placeholder);
659
+ return placeholder ? `${label} (${placeholder})` : label;
660
+ }
661
+ function methodSummary(m) {
662
+ return {
663
+ authentication_id: m.authenticationId,
664
+ authentication_type: m.authenticationType,
665
+ authentication_name: m.authenticationName,
666
+ requires_oauth: m.requiresOAuthSignIn,
667
+ fields: m.connectionFields.map(fieldSummary)
668
+ };
669
+ }
670
+ function fieldSummary(f) {
671
+ return {
672
+ field_name: f.fieldName,
673
+ is_required: f.isRequired,
674
+ is_password: f.isPassword,
675
+ description: clean(f.fieldDescription),
676
+ default: clean(f.defaultValue),
677
+ list_values: clean(f.listValues)
678
+ };
679
+ }
680
+ function objectSummary(o) {
681
+ return {
682
+ object_id: o.objectId,
683
+ name: o.name,
684
+ type: o.type,
685
+ is_selected: o.isSelected
686
+ };
372
687
  }
373
688
  function registerConnect(program) {
374
- const cmd = program.command("connect").description("Open the Engini connections page in your browser.");
689
+ const cmd = program.command("connect").description("Create a connection (interactive/agent-resumable), or open the connections page.").argument("[application]", "Application slug to connect").option("--auth <id>", "Authentication method id").option("--name <name>", "Connection name").option("--field <spec>", "Credential field: key=value (repeatable)", collect).option("--object <id>", "Object id to select (repeatable)", collect).option("--no-objects", "Skip object selection").option("--oauth-state <state>", "Resume an OAuth2 sign-in by its state token").option("--connection <id>", "Resume object selection for an existing connection id").option("--no-wait", "Return early instead of waiting for async jobs").option("--timeout <seconds>", "Seconds to wait before timing out").option("--poll-interval <seconds>", "Seconds between polls");
375
690
  cmd.addHelpText(
376
691
  "after",
377
- "\nExamples:\n engini connect\n engini connect --json | jq -r '.url'"
692
+ [
693
+ "",
694
+ "Examples:",
695
+ " engini connect # open the web connections page",
696
+ " engini connect monday # interactive walkthrough (TTY)",
697
+ " engini connect monday --field ApiKey=\u2026 --name 'My Monday'",
698
+ " engini connect monday --json # agent: prints the next step + exit 5",
699
+ " engini connect outlook --oauth-state <state> # resume an OAuth sign-in",
700
+ " engini connect monday --connection 42 --object 5 # resume object selection"
701
+ ].join("\n")
378
702
  );
703
+ addUniversalOptions(cmd, { mutating: true });
704
+ cmd.action(async (application, opts, command) => {
705
+ await runCommand(
706
+ command,
707
+ opts,
708
+ true,
709
+ () => connectBody(application, opts)
710
+ );
711
+ });
712
+ }
713
+
714
+ // src/connections/check.ts
715
+ async function checkBody(connectionId) {
716
+ const id = parseId(connectionId);
717
+ const result = await apiErrors(async () => {
718
+ const client = buildClient();
719
+ return client.connections.check(id);
720
+ });
721
+ const alive = checkAlive(result);
722
+ if (alive === false) {
723
+ fail(1 /* GENERIC */, `Connection ${id} failed its liveness check.`);
724
+ }
725
+ printOutput({ connection_id: id, is_alive: alive, check: result });
726
+ }
727
+ function registerConnectionsCheck(connections) {
728
+ const cmd = connections.command("check").description("Test a connection's liveness.").argument("[connection_id]", "Connection id");
729
+ cmd.addHelpText("after", "\nExamples:\n engini connections check 42");
379
730
  addUniversalOptions(cmd);
380
- cmd.action(async (opts, command) => {
381
- await runCommand(command, opts, false, () => connectBody());
731
+ cmd.action(async (id, opts, command) => {
732
+ await runCommand(command, opts, false, () => checkBody(id));
733
+ });
734
+ }
735
+
736
+ // src/connections/create.ts
737
+ function summary(c) {
738
+ return {
739
+ connection_id: c.connectionId,
740
+ connection_name: c.connectionName,
741
+ application_slug: c.applicationSlug,
742
+ is_alive: clean(c.isAlive),
743
+ use_select_db_objects: clean(c.useSelectDBObjects)
744
+ };
745
+ }
746
+ async function createBody(application, opts) {
747
+ if (!application) fail(2 /* USAGE */, "Missing required argument 'application'.");
748
+ if (!opts.auth) fail(2 /* USAGE */, "Missing required option '--auth'.");
749
+ if (!opts.name) fail(2 /* USAGE */, "Missing required option '--name'.");
750
+ const auth = Number(opts.auth);
751
+ if (!Number.isInteger(auth)) fail(2 /* USAGE */, "--auth must be an integer.");
752
+ const fields = parseFields(opts.field);
753
+ if (dryRun()) {
754
+ printOutput({
755
+ would_create: {
756
+ application_slug: application,
757
+ connection_name: opts.name,
758
+ authentication_id: auth,
759
+ fields: Object.fromEntries(Object.entries(fields).map(([k, v]) => [k, maskSecret(v)])),
760
+ description: opts.description ?? null
761
+ }
762
+ });
763
+ return;
764
+ }
765
+ const conn = await apiErrors(async () => {
766
+ const client = buildClient();
767
+ return client.connections.create(application, opts.name, auth, fields, {
768
+ description: opts.description
769
+ });
770
+ });
771
+ printOutput(summary(conn));
772
+ }
773
+ function registerConnectionsCreate(connections) {
774
+ const cmd = connections.command("create").description("Create a direct-credential connection.").argument("[application]", "Application slug").option("--auth <id>", "Authentication method id").option("--name <name>", "Connection name").option("--field <spec>", "Credential field: key=value (repeatable)", collect).option("--description <text>", "Connection description");
775
+ cmd.addHelpText(
776
+ "after",
777
+ "\nExamples:\n engini connections create slack --auth 2 --name Sales --field token=xoxb-1"
778
+ );
779
+ addUniversalOptions(cmd, { mutating: true });
780
+ cmd.action(async (application, opts, command) => {
781
+ await runCommand(
782
+ command,
783
+ opts,
784
+ true,
785
+ () => createBody(application, opts)
786
+ );
382
787
  });
383
788
  }
384
789
 
@@ -399,7 +804,7 @@ function detail2(c) {
399
804
  updated_date: clean(c.updatedDate)
400
805
  };
401
806
  }
402
- function parseId(value) {
807
+ function parseId2(value) {
403
808
  if (!value) {
404
809
  fail(2 /* USAGE */, "Missing required argument 'connection_id'.");
405
810
  }
@@ -410,7 +815,7 @@ function parseId(value) {
410
815
  return id;
411
816
  }
412
817
  async function getBody2(connectionId) {
413
- const id = parseId(connectionId);
818
+ const id = parseId2(connectionId);
414
819
  const connection = await apiErrors(async () => {
415
820
  const client = buildClient();
416
821
  return client.connections.get(id);
@@ -457,11 +862,196 @@ function registerConnectionsList(connections) {
457
862
  });
458
863
  }
459
864
 
865
+ // src/connections/oauth-complete.ts
866
+ function summary2(c) {
867
+ return {
868
+ connection_id: c.connectionId,
869
+ connection_name: c.connectionName,
870
+ application_slug: c.applicationSlug,
871
+ is_alive: clean(c.isAlive),
872
+ use_select_db_objects: clean(c.useSelectDBObjects)
873
+ };
874
+ }
875
+ async function oauthCompleteBody(application, opts) {
876
+ if (!application) fail(2 /* USAGE */, "Missing required argument 'application'.");
877
+ if (!opts.auth) fail(2 /* USAGE */, "Missing required option '--auth'.");
878
+ if (!opts.state) fail(2 /* USAGE */, "Missing required option '--state'.");
879
+ const auth = Number(opts.auth);
880
+ if (!Number.isInteger(auth)) fail(2 /* USAGE */, "--auth must be an integer.");
881
+ const name = opts.name ?? `${application} connection`;
882
+ if (dryRun()) {
883
+ printOutput({ would_complete: { application, authentication_id: auth, state: opts.state } });
884
+ return;
885
+ }
886
+ const conn = await apiErrors(async () => {
887
+ const client = buildClient();
888
+ const token = await pollAccessToken(client, opts.state, {
889
+ timeout: Number(opts.timeout ?? 300),
890
+ interval: Number(opts.pollInterval ?? 2)
891
+ });
892
+ progress(`Creating connection '${name}'\u2026`);
893
+ return client.connections.create(application, name, auth, oauthFields(token));
894
+ });
895
+ printOutput(summary2(conn));
896
+ }
897
+ function registerConnectionsOauthComplete(connections) {
898
+ const cmd = connections.command("oauth-complete").description("Finish an OAuth2 sign-in and create the connection.").argument("[application]", "Application slug").option("--auth <id>", "Authentication method id").option("--state <state>", "State token from `sign-in-url`").option("--name <name>", "Connection name").option("--timeout <seconds>", "Seconds to wait before timing out").option("--poll-interval <seconds>", "Seconds between polls");
899
+ cmd.addHelpText(
900
+ "after",
901
+ "\nExamples:\n engini connections oauth-complete outlook --auth 0 --state <state>"
902
+ );
903
+ addUniversalOptions(cmd, { mutating: true });
904
+ cmd.action(
905
+ async (application, opts, command) => {
906
+ await runCommand(
907
+ command,
908
+ opts,
909
+ true,
910
+ () => oauthCompleteBody(application, opts)
911
+ );
912
+ }
913
+ );
914
+ }
915
+
916
+ // src/connections/objects.ts
917
+ function summary3(o) {
918
+ return {
919
+ object_id: o.objectId,
920
+ name: o.name,
921
+ type: o.type,
922
+ is_selected: o.isSelected
923
+ };
924
+ }
925
+ async function objectsBody(connectionId, opts) {
926
+ const id = parseId(connectionId);
927
+ const objs = await apiErrors(async () => {
928
+ const client = buildClient();
929
+ return client.connections.objects(id, { name: opts.name });
930
+ });
931
+ printOutput(objs.map(summary3));
932
+ }
933
+ function registerConnectionsObjects(connections) {
934
+ const cmd = connections.command("objects").description("List the objects a connection exposes.").argument("[connection_id]", "Connection id").option("--name <filter>", "Filter objects by name");
935
+ cmd.addHelpText("after", "\nExamples:\n engini connections objects 42 --name leads");
936
+ addUniversalOptions(cmd);
937
+ cmd.action(async (id, opts, command) => {
938
+ await runCommand(command, opts, false, () => objectsBody(id, opts));
939
+ });
940
+ }
941
+
942
+ // src/connections/refresh.ts
943
+ async function refreshBody(connectionId, opts) {
944
+ const id = parseId(connectionId);
945
+ if (dryRun()) {
946
+ printOutput({ would_refresh: { connection_id: id } });
947
+ return;
948
+ }
949
+ const status = await apiErrors(async () => {
950
+ const client = buildClient();
951
+ await client.connections.refresh(id);
952
+ return pollRefresh(client, id, {
953
+ wait: opts.wait !== false,
954
+ timeout: Number(opts.timeout ?? 300),
955
+ interval: Number(opts.pollInterval ?? 2)
956
+ });
957
+ });
958
+ printOutput({ connection_id: id, status });
959
+ }
960
+ function registerConnectionsRefresh(connections) {
961
+ const cmd = connections.command("refresh").description("Refresh a connection's objects (async).").argument("[connection_id]", "Connection id").option("--no-wait", "Return immediately instead of waiting for the refresh").option("--timeout <seconds>", "Seconds to wait before timing out").option("--poll-interval <seconds>", "Seconds between status polls");
962
+ cmd.addHelpText(
963
+ "after",
964
+ "\nExamples:\n engini connections refresh 42\n engini connections refresh 42 --no-wait"
965
+ );
966
+ addUniversalOptions(cmd, { mutating: true });
967
+ cmd.action(async (id, opts, command) => {
968
+ await runCommand(command, opts, true, () => refreshBody(id, opts));
969
+ });
970
+ }
971
+
972
+ // src/connections/select-objects.ts
973
+ async function selectBody(connectionId, opts) {
974
+ const id = parseId(connectionId);
975
+ const objectIds = (opts.object ?? []).map((value) => {
976
+ const n = Number(value);
977
+ if (!Number.isInteger(n)) fail(2 /* USAGE */, `--object must be an integer, got '${value}'.`);
978
+ return n;
979
+ });
980
+ if (objectIds.length === 0) fail(2 /* USAGE */, "Pass at least one --object <id>.");
981
+ if (dryRun()) {
982
+ printOutput({ would_select: { connection_id: id, object_ids: objectIds } });
983
+ return;
984
+ }
985
+ const status = await apiErrors(async () => {
986
+ const client = buildClient();
987
+ await client.connections.selectObjects(id, objectIds);
988
+ return pollRefresh(client, id, {
989
+ wait: opts.wait !== false,
990
+ timeout: Number(opts.timeout ?? 300),
991
+ interval: Number(opts.pollInterval ?? 2)
992
+ });
993
+ });
994
+ printOutput({
995
+ connection_id: id,
996
+ objects_selected: objectIds.length,
997
+ status
998
+ });
999
+ }
1000
+ function registerConnectionsSelectObjects(connections) {
1001
+ const cmd = connections.command("select-objects").description("Choose which objects a connection syncs (async).").argument("[connection_id]", "Connection id").option("--object <id>", "Object id to select (repeatable)", collect).option("--no-wait", "Return immediately instead of waiting for the refresh").option("--timeout <seconds>", "Seconds to wait before timing out").option("--poll-interval <seconds>", "Seconds between status polls");
1002
+ cmd.addHelpText(
1003
+ "after",
1004
+ "\nExamples:\n engini connections select-objects 42 --object 5 --object 9"
1005
+ );
1006
+ addUniversalOptions(cmd, { mutating: true });
1007
+ cmd.action(async (id, opts, command) => {
1008
+ await runCommand(command, opts, true, () => selectBody(id, opts));
1009
+ });
1010
+ }
1011
+
1012
+ // src/connections/sign-in-url.ts
1013
+ async function signInUrlBody(application, opts) {
1014
+ if (!application) fail(2 /* USAGE */, "Missing required argument 'application'.");
1015
+ if (!opts.auth) fail(2 /* USAGE */, "Missing required option '--auth'.");
1016
+ const auth = Number(opts.auth);
1017
+ if (!Number.isInteger(auth)) fail(2 /* USAGE */, "--auth must be an integer.");
1018
+ const fields = opts.field ? parseFields(opts.field) : void 0;
1019
+ const resp = await apiErrors(async () => {
1020
+ const client = buildClient();
1021
+ return client.connections.getSignInUrl(application, auth, { fields });
1022
+ });
1023
+ printOutput({
1024
+ sign_in_url: resp.signInUrl,
1025
+ state: resp.state,
1026
+ resume: `engini connections oauth-complete ${application} --auth ${auth} --state ${resp.state}`
1027
+ });
1028
+ }
1029
+ function registerConnectionsSignInUrl(connections) {
1030
+ const cmd = connections.command("sign-in-url").description("Start an OAuth2 sign-in (returns the URL + state).").argument("[application]", "Application slug").option("--auth <id>", "Authentication method id").option("--field <spec>", "Pre-sign-in field: key=value (repeatable)", collect);
1031
+ cmd.addHelpText("after", "\nExamples:\n engini connections sign-in-url outlook --auth 0");
1032
+ addUniversalOptions(cmd);
1033
+ cmd.action(async (application, opts, command) => {
1034
+ await runCommand(
1035
+ command,
1036
+ opts,
1037
+ false,
1038
+ () => signInUrlBody(application, opts)
1039
+ );
1040
+ });
1041
+ }
1042
+
460
1043
  // src/connections/index.ts
461
1044
  function registerConnections(program) {
462
- const connections = program.command("connections").description("List, inspect, and remove connections.");
1045
+ const connections = program.command("connections").description("List, inspect, create, and remove connections.");
463
1046
  registerConnectionsList(connections);
464
1047
  registerConnectionsGet(connections);
1048
+ registerConnectionsCreate(connections);
1049
+ registerConnectionsCheck(connections);
1050
+ registerConnectionsRefresh(connections);
1051
+ registerConnectionsObjects(connections);
1052
+ registerConnectionsSelectObjects(connections);
1053
+ registerConnectionsSignInUrl(connections);
1054
+ registerConnectionsOauthComplete(connections);
465
1055
  const del = connections.command("delete").description("Remove a connection.").argument("[connection_id]", "Connection id");
466
1056
  addUniversalOptions(del, { mutating: true });
467
1057
  del.action(async (_id, opts, command) => {
@@ -523,10 +1113,22 @@ ACCOUNT
523
1113
  whoami Show the authenticated user/company.
524
1114
 
525
1115
  CONNECTIONS
1116
+ connect [<app>] Create a connection \u2014 interactive on a TTY, or
1117
+ agent-resumable when piped (prints {need, resume}).
1118
+ Resume with --oauth-state <state> (OAuth) or
1119
+ --connection <id> (object selection). No app \u2192 web page.
526
1120
  connections list [--application <slug>] List your connections.
527
1121
  connections get <id> Inspect a connection.
1122
+ connections create <app> --auth <id> --name <n> --field k=v
1123
+ Create a direct-credential connection.
1124
+ connections sign-in-url <app> --auth <id> Start an OAuth2 sign-in (returns URL + state).
1125
+ connections oauth-complete <app> --auth <id> --state <state>
1126
+ Finish an OAuth2 sign-in and create the connection.
1127
+ connections check <id> Test a connection's liveness.
1128
+ connections refresh <id> [--no-wait] Refresh a connection's objects (async).
1129
+ connections objects <id> List the objects a connection exposes.
1130
+ connections select-objects <id> --object <id> Choose which objects to sync (async).
528
1131
  connections delete <id> Remove a connection. (coming soon)
529
- connect Open the Engini connections page in your browser.
530
1132
 
531
1133
  OUTPUT & EXIT CODES
532
1134
  Output adapts to context: human-readable on a TTY, compact JSON when piped, pretty
@@ -667,20 +1269,20 @@ async function loginBody(opts) {
667
1269
  }
668
1270
  config.api_key = apiKey;
669
1271
  config.auth_kind = "api-key";
670
- const summary2 = {
1272
+ const summary5 = {
671
1273
  auth_kind: "api-key",
672
1274
  credential: maskSecret(apiKey),
673
1275
  api_url: config.api_url
674
1276
  };
675
1277
  if (dryRun()) {
676
- printOutput({ would_store: summary2 });
1278
+ printOutput({ would_store: summary5 });
677
1279
  return;
678
1280
  }
679
1281
  if (hadCredentials) {
680
1282
  await confirmOrFail("Credentials already exist. Overwrite?", { force: Boolean(opts.force) });
681
1283
  }
682
1284
  saveConfig(config);
683
- printOutput({ stored: summary2 });
1285
+ printOutput({ stored: summary5 });
684
1286
  }
685
1287
  function registerLogin(program) {
686
1288
  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");
@@ -1282,7 +1884,7 @@ function registerTools(program) {
1282
1884
  }
1283
1885
 
1284
1886
  // src/whoami.ts
1285
- function summary(me) {
1887
+ function summary4(me) {
1286
1888
  return {
1287
1889
  full_name: clean(me.fullName),
1288
1890
  email: clean(me.email),
@@ -1296,7 +1898,7 @@ async function whoamiBody() {
1296
1898
  const client = buildClient();
1297
1899
  return client.auth.whoami();
1298
1900
  });
1299
- printOutput(summary(me));
1901
+ printOutput(summary4(me));
1300
1902
  }
1301
1903
  function registerWhoami(program) {
1302
1904
  const cmd = program.command("whoami").description("Report the authenticated user/company.");
@@ -1308,7 +1910,7 @@ function registerWhoami(program) {
1308
1910
  }
1309
1911
 
1310
1912
  // src/version.ts
1311
- var VERSION = true ? "0.7.0" : "0.0.0";
1913
+ var VERSION = true ? "0.8.1" : "0.0.0";
1312
1914
 
1313
1915
  // src/main.ts
1314
1916
  function buildProgram() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@engini/cli",
3
- "version": "0.7.0",
3
+ "version": "0.8.1",
4
4
  "description": "Engini CLI — machine-first command line over the Engini Public API",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -21,7 +21,7 @@
21
21
  "test": "vitest run"
22
22
  },
23
23
  "dependencies": {
24
- "@engini/sdk": "^0.7.0",
24
+ "@engini/sdk": "^0.8.0",
25
25
  "commander": "^12.1.0",
26
26
  "smol-toml": "^1.3.0"
27
27
  },