@engini/cli 0.35.0 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,408 +1,60 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ CLIENT_ID,
4
+ CliError,
5
+ DEFAULT_API_URL,
6
+ Exit,
7
+ OAUTH_FIELDS,
8
+ PromptCancelled,
9
+ PromptStreamEnded,
10
+ addUniversalOptions,
11
+ assertNoLegacyKeyEnv,
12
+ checkedPair,
13
+ configPath,
14
+ confirm,
15
+ confirmOrFail,
16
+ dryRun,
17
+ ensureFreshSession,
18
+ fail,
19
+ findScope,
20
+ flattenScopes,
21
+ getProfile,
22
+ isInteractive,
23
+ isTty,
24
+ loadConfig,
25
+ mapCommanderExitCode,
26
+ maskSecret,
27
+ note,
28
+ openBrowser,
29
+ outputFlags,
30
+ printOutput,
31
+ profileDefaults,
32
+ profileResumeFlag,
33
+ progress,
34
+ promptHidden,
35
+ promptText,
36
+ readStdin,
37
+ resolveActive,
38
+ resolvePair,
39
+ revokeSession,
40
+ runCommand,
41
+ sandboxKey,
42
+ selectedProfile,
43
+ updateConfig,
44
+ validateProfileName,
45
+ withRefreshLock
46
+ } from "./chunk-XNKWQPRX.js";
2
47
 
3
48
  // src/index.ts
4
49
  import { realpathSync } from "fs";
5
50
  import { pathToFileURL } from "url";
6
51
 
7
- // src/prompt.ts
8
- import { spawn } from "child_process";
9
- import { createInterface } from "readline";
10
- function openBrowser(url) {
11
- const command = process.platform === "win32" ? "start" : process.platform === "darwin" ? "open" : "xdg-open";
12
- const args = process.platform === "win32" ? ["", url] : [url];
13
- try {
14
- const child = spawn(command, args, { stdio: "ignore", detached: true, shell: process.platform === "win32" });
15
- child.on("error", () => {
16
- });
17
- child.unref();
18
- } catch {
19
- }
20
- }
21
- var PromptCancelled = class extends Error {
22
- constructor() {
23
- super("cancelled");
24
- this.name = "PromptCancelled";
25
- }
26
- };
27
- var PromptStreamEnded = class extends Error {
28
- constructor() {
29
- super("stdin ended before an answer was given");
30
- this.name = "PromptStreamEnded";
31
- }
32
- };
33
- async function readStdin(stream = process.stdin) {
34
- const chunks = [];
35
- for await (const chunk of stream) {
36
- chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
37
- }
38
- return Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/, "");
39
- }
40
- function ask(rl, question) {
41
- return new Promise((resolve, reject) => {
42
- let answered = false;
43
- rl.question(question, (value) => {
44
- answered = true;
45
- resolve(value);
46
- });
47
- rl.once("close", () => {
48
- if (!answered) reject(new PromptStreamEnded());
49
- });
50
- });
51
- }
52
- async function confirm(question) {
53
- const rl = createInterface({ input: process.stdin, output: process.stdout });
54
- try {
55
- const answer = (await ask(rl, `${question} [y/N] `)).trim().toLowerCase();
56
- return answer === "y" || answer === "yes";
57
- } finally {
58
- rl.close();
59
- }
60
- }
61
- async function promptText(label, fallback = "") {
62
- const suffix = fallback ? ` [${fallback}]` : "";
63
- const rl = createInterface({ input: process.stdin, output: process.stdout });
64
- try {
65
- const answer = (await ask(rl, `${label}${suffix}: `)).trim();
66
- return answer || fallback;
67
- } finally {
68
- rl.close();
69
- }
70
- }
71
- var ESC = "\x1B";
72
- var CTRL_C = "";
73
- var CTRL_D = "";
74
- var CTRL_U = "";
75
- var DEL = "\x7F";
76
- var BACKSPACE = "\b";
77
- var MAX_ESCAPE_LENGTH = 256;
78
- function escapeKind(pending) {
79
- if (pending.length < 2) return "incomplete";
80
- const second = pending[1];
81
- if (second !== "[" && second !== "O") return "two-char";
82
- if (pending.length < 3) return "incomplete";
83
- const last = pending[pending.length - 1];
84
- return last >= "@" && last <= "~" ? "csi" : "incomplete";
85
- }
86
- function promptHidden(label, opts = {}) {
87
- const streams = opts.streams ?? { input: process.stdin, output: process.stdout };
88
- const { input, output } = streams;
89
- const wasRaw = Boolean(input.isRaw);
90
- let raw = false;
91
- if (input.isTTY && typeof input.setRawMode === "function") {
92
- try {
93
- input.setRawMode(true);
94
- raw = true;
95
- } catch {
96
- raw = false;
97
- }
98
- }
99
- const mask = (opts.mask ?? true) && raw;
100
- return new Promise((resolve, reject) => {
101
- let settled = false;
102
- const write = (s) => {
103
- try {
104
- output.write(s);
105
- } catch {
106
- }
107
- };
108
- let restored = false;
109
- const restore = () => {
110
- if (restored) return;
111
- restored = true;
112
- try {
113
- if (raw) input.setRawMode?.(wasRaw);
114
- } catch {
115
- }
116
- try {
117
- input.pause();
118
- } catch {
119
- }
120
- };
121
- const usingRealStdin = input === process.stdin;
122
- if (usingRealStdin) process.once("exit", restore);
123
- const detach = () => {
124
- input.removeListener("data", onData);
125
- input.removeListener("end", onEnd);
126
- input.removeListener("error", onEnd);
127
- if (usingRealStdin) process.removeListener("exit", restore);
128
- };
129
- const finish = (err, result) => {
130
- if (settled) return;
131
- settled = true;
132
- detach();
133
- restore();
134
- write("\n");
135
- if (err) reject(err);
136
- else resolve(result);
137
- };
138
- function onEnd() {
139
- finish(new PromptStreamEnded());
140
- }
141
- let buf = "";
142
- let pending = "";
143
- const eraseOne = () => {
144
- const cps = Array.from(buf);
145
- cps.pop();
146
- buf = cps.join("");
147
- };
148
- const clearLine = () => {
149
- if (mask) write("\b \b".repeat(Array.from(buf).length));
150
- buf = "";
151
- };
152
- const onData = (chunk) => {
153
- const chars = Array.from(chunk);
154
- let discarding = false;
155
- for (let i = 0; i < chars.length; i++) {
156
- const ch = chars[i];
157
- if (ch === CTRL_C || ch === CTRL_D) return finish(new PromptCancelled());
158
- if (ch === "\r" || ch === "\n") {
159
- const rest = chars.slice(i + 1).join("");
160
- return finish(null, { value: buf.trim(), truncated: rest.trim().length > 0 });
161
- }
162
- if (discarding) continue;
163
- if (pending) {
164
- pending += ch;
165
- if (pending.length > MAX_ESCAPE_LENGTH) {
166
- clearLine();
167
- pending = "";
168
- discarding = true;
169
- continue;
170
- }
171
- const kind = escapeKind(pending);
172
- if (kind === "csi") {
173
- pending = "";
174
- } else if (kind === "two-char") {
175
- if (pending[1] === ESC) {
176
- pending = ESC;
177
- continue;
178
- }
179
- clearLine();
180
- pending = "";
181
- }
182
- continue;
183
- }
184
- if (ch === ESC) {
185
- pending = ch;
186
- continue;
187
- }
188
- if (ch === DEL || ch === BACKSPACE) {
189
- if (buf.length > 0) {
190
- eraseOne();
191
- if (mask) write("\b \b");
192
- }
193
- continue;
194
- }
195
- if (ch === CTRL_U) {
196
- clearLine();
197
- continue;
198
- }
199
- if (ch < " ") continue;
200
- buf += ch;
201
- if (mask) write("*");
202
- }
203
- };
204
- try {
205
- input.resume();
206
- input.setEncoding("utf8");
207
- write(`${label}: `);
208
- input.on("data", onData);
209
- input.on("end", onEnd);
210
- input.on("error", onEnd);
211
- } catch (err) {
212
- finish(err instanceof Error ? err : new Error(String(err)));
213
- }
214
- });
215
- }
216
-
217
- // src/conventions.ts
218
- var Exit = /* @__PURE__ */ ((Exit2) => {
219
- Exit2[Exit2["OK"] = 0] = "OK";
220
- Exit2[Exit2["GENERIC"] = 1] = "GENERIC";
221
- Exit2[Exit2["USAGE"] = 2] = "USAGE";
222
- Exit2[Exit2["AUTH"] = 3] = "AUTH";
223
- Exit2[Exit2["NOT_FOUND"] = 4] = "NOT_FOUND";
224
- Exit2[Exit2["VALIDATION"] = 5] = "VALIDATION";
225
- Exit2[Exit2["TIMEOUT"] = 124] = "TIMEOUT";
226
- return Exit2;
227
- })(Exit || {});
228
- var ERROR_NAMES = {
229
- [1 /* GENERIC */]: "Error",
230
- [2 /* USAGE */]: "UsageError",
231
- [3 /* AUTH */]: "AuthError",
232
- [4 /* NOT_FOUND */]: "ResourceNotFound",
233
- [5 /* VALIDATION */]: "ValidationError",
234
- [124 /* TIMEOUT */]: "Timeout"
235
- };
236
- var CliError = class extends Error {
237
- constructor(code) {
238
- super(`CliExit(${code})`);
239
- this.code = code;
240
- this.name = "CliError";
241
- }
242
- code;
243
- };
244
- function isTty() {
245
- return Boolean(process.stdout.isTTY);
246
- }
247
- function isInteractive() {
248
- return Boolean(process.stdout.isTTY && process.stdin.isTTY);
249
- }
250
- var context = { forceJson: false, quiet: false, dryRun: false };
251
- function setOutputContext(ctx) {
252
- context = ctx;
253
- }
254
- function dryRun() {
255
- return context.dryRun;
256
- }
257
- function outputFlags() {
258
- return { forceJson: context.forceJson, quiet: context.quiet };
259
- }
260
- function formatValue(value) {
261
- return typeof value === "string" ? value : JSON.stringify(value);
262
- }
263
- function pretty(obj) {
264
- if (obj !== null && typeof obj === "object" && !Array.isArray(obj)) {
265
- for (const [key, value] of Object.entries(obj)) {
266
- console.log(`${key}: ${formatValue(value)}`);
267
- }
268
- } else if (Array.isArray(obj)) {
269
- for (const item of obj) {
270
- console.log(formatValue(item));
271
- }
272
- } else {
273
- console.log(formatValue(obj));
274
- }
275
- }
276
- function printOutput(obj) {
277
- if (context.forceJson) {
278
- console.log(JSON.stringify(obj, null, 2));
279
- } else if (!isTty()) {
280
- console.log(JSON.stringify(obj));
281
- } else {
282
- pretty(obj);
283
- }
284
- }
285
- function progress(message) {
286
- if (isTty() && !context.quiet) console.error(message);
287
- }
288
- function fail(code, message, hint2, extra) {
289
- if (isTty()) {
290
- console.error(`Error: ${message}`);
291
- if (hint2) console.error(`Hint: ${hint2}`);
292
- if (extra?.diagnostics?.length) {
293
- for (const line of diagnosticTable(extra.diagnostics)) console.error(line);
294
- }
295
- } else {
296
- const payload = {
297
- error: ERROR_NAMES[code] ?? "Error",
298
- message,
299
- exit_code: code
300
- };
301
- if (hint2) payload.hint = hint2;
302
- if (extra?.code !== void 0) payload.code = extra.code;
303
- if (extra?.path) payload.path = extra.path;
304
- if (extra?.currentRevisionId != null) payload.current_revision_id = extra.currentRevisionId;
305
- if (extra?.diagnostics?.length) payload.diagnostics = extra.diagnostics;
306
- console.error(JSON.stringify(payload));
307
- }
308
- throw new CliError(code);
309
- }
310
- function diagnosticTable(rows) {
311
- const header = ["SEVERITY", "CODE", "STEP", "FIELD", "MESSAGE"];
312
- const body = rows.map((d) => [d.severity, d.code, d.stepKey ?? "-", d.field ?? "-", d.message]);
313
- const widths = header.map((h, i) => Math.max(h.length, ...body.map((r) => r[i].length)));
314
- const line = (cells) => cells.map((c, i) => i === cells.length - 1 ? c : c.padEnd(widths[i])).join(" ");
315
- return [line(header), ...body.map(line)];
316
- }
317
- function mapCommanderExitCode(exitCode) {
318
- const code = exitCode ?? 1;
319
- return code === 0 ? 0 /* OK */ : 2 /* USAGE */;
320
- }
321
- function maskSecret(value) {
322
- return value.length > 8 ? `${value.slice(0, 4)}\u2026${value.slice(-4)}` : "****";
323
- }
324
- async function confirmOrFail(prompt, opts) {
325
- if (opts.force) return;
326
- if (isInteractive()) {
327
- if (!await confirm(prompt)) {
328
- throw new CliError(0 /* OK */);
329
- }
330
- return;
331
- }
332
- fail(2 /* USAGE */, `${prompt} Pass --force to proceed non-interactively.`);
333
- }
334
- var SCHEMA_VERSION = "1";
335
- var UNIVERSAL_FLAGS = /* @__PURE__ */ new Set(["--json", "--quiet", "--schema", "--dry-run"]);
336
- function schemaKey(name) {
337
- return name.replace(/^--?/, "").replace(/-/g, "_");
338
- }
339
- function optionTakesValue(option) {
340
- return option.required || option.optional;
341
- }
342
- function buildSchema(command, mutating) {
343
- const args = {};
344
- for (const arg of command.registeredArguments) {
345
- args[schemaKey(arg.name())] = { type: "string", required: arg.required };
346
- }
347
- for (const option of command.options) {
348
- if (UNIVERSAL_FLAGS.has(option.long ?? "")) continue;
349
- const key = schemaKey(option.long ?? option.short ?? "");
350
- args[key] = {
351
- type: optionTakesValue(option) ? "string" : "boolean",
352
- required: option.mandatory
353
- };
354
- }
355
- return {
356
- $schema: "https://json-schema.org/draft/2020-12/schema",
357
- version: SCHEMA_VERSION,
358
- mutating,
359
- args,
360
- output: null
361
- };
362
- }
363
- function addUniversalOptions(command, opts = {}) {
364
- command.option("--json", "Pretty JSON output").option("--quiet", "Suppress non-essential output").option("--schema", "Print this command's args/output schema as JSON");
365
- if (opts.mutating) {
366
- command.option("--dry-run", "Preview without executing");
367
- }
368
- return command;
369
- }
370
- async function runCommand(command, opts, mutating, body) {
371
- if (opts.schema) {
372
- console.log(JSON.stringify(buildSchema(command, mutating), null, 2));
373
- throw new CliError(0 /* OK */);
374
- }
375
- setOutputContext({
376
- forceJson: Boolean(opts.json),
377
- quiet: Boolean(opts.quiet),
378
- dryRun: Boolean(opts.dryRun)
379
- });
380
- try {
381
- await body();
382
- } catch (err) {
383
- if (err instanceof PromptCancelled) {
384
- fail(2 /* USAGE */, "Cancelled.");
385
- }
386
- if (err instanceof PromptStreamEnded) {
387
- fail(
388
- 2 /* USAGE */,
389
- "Input ended before the prompt was answered.",
390
- "Pass the required values as flags when running non-interactively."
391
- );
392
- }
393
- throw err;
394
- }
395
- }
396
-
397
52
  // src/main.ts
398
53
  import { Command } from "commander";
399
54
 
400
55
  // src/http.ts
401
56
  import {
402
57
  Engini,
403
- ENV_API_KEY_VAR,
404
- ENV_COMPANY_TOKEN_VAR,
405
- ENV_TOKEN_VAR,
406
58
  EnginiAuthError,
407
59
  EnginiBuilderError,
408
60
  EnginiConflictError,
@@ -417,75 +69,59 @@ import {
417
69
  EnginiValidationError
418
70
  } from "@engini/sdk";
419
71
 
420
- // src/config.ts
421
- import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
422
- import { homedir } from "os";
423
- import { dirname, join } from "path";
424
- import { parse, stringify } from "smol-toml";
425
- var CONFIG_SCHEMA_VERSION = 1;
426
- function defaultConfig() {
427
- return {
428
- config_schema_version: CONFIG_SCHEMA_VERSION,
429
- api_url: "https://api.engini.io",
430
- identity_url: "https://app.engini.io"
431
- };
432
- }
433
- function configPath() {
434
- const base = process.platform === "win32" ? process.env.APPDATA ?? homedir() : process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config");
435
- return join(base, "engini", "config.toml");
436
- }
437
- function asString(value) {
438
- return typeof value === "string" ? value : void 0;
439
- }
440
- function loadConfig(path = configPath()) {
441
- if (!existsSync(path)) return defaultConfig();
442
- const data = parse(readFileSync(path, "utf8"));
443
- const config = defaultConfig();
444
- if (typeof data.config_schema_version === "number") {
445
- config.config_schema_version = data.config_schema_version;
446
- }
447
- config.api_url = asString(data.api_url) ?? config.api_url;
448
- config.identity_url = asString(data.identity_url) ?? config.identity_url;
449
- config.api_key = asString(data.api_key);
450
- config.api_token = asString(data.api_token);
451
- config.company_token = asString(data.company_token);
452
- if (data.auth_kind === "api-key" || data.auth_kind === "jwt") {
453
- config.auth_kind = data.auth_kind;
454
- }
455
- return config;
456
- }
457
- function saveConfig(config, path = configPath()) {
458
- mkdirSync(dirname(path), { recursive: true });
459
- const data = {};
460
- for (const [key, value] of Object.entries(config)) {
461
- if (value !== void 0) data[key] = value;
462
- }
463
- writeFileSync(path, stringify(data), { mode: 384 });
464
- if (process.platform !== "win32") chmodSync(path, 384);
465
- }
466
-
467
72
  // src/version.ts
468
- var VERSION = true ? "0.35.0" : "0.0.0";
73
+ var VERSION = true ? "0.36.0" : "0.0.0";
469
74
 
470
75
  // src/http.ts
471
76
  var USER_AGENT_PREFIX = `engini-cli/${VERSION}`;
472
- function buildClient(overrides = {}) {
473
- const config = loadConfig();
474
- const key = overrides.apiKey ?? process.env[ENV_API_KEY_VAR] ?? config.api_key;
475
- if (key) {
476
- return new Engini({ apiKey: key, baseUrl: config.api_url, userAgentPrefix: USER_AGENT_PREFIX });
77
+ function clientFor(creds, apiUrl, pair) {
78
+ return new Engini({
79
+ ...creds,
80
+ baseUrl: apiUrl,
81
+ userAgentPrefix: USER_AGENT_PREFIX,
82
+ ...pair && { workspaceId: pair.workspaceId, environmentId: pair.environmentId }
83
+ });
84
+ }
85
+ function buildClient() {
86
+ assertNoLegacyKeyEnv();
87
+ const active = resolveActive();
88
+ const { profile } = active;
89
+ const { pair } = resolvePair(active);
90
+ if (active.source === "env-credential") {
91
+ const token = process.env.ENGINI_API_TOKEN;
92
+ if (profile.api_url !== DEFAULT_API_URL) {
93
+ note(`Using ${profile.api_url} (from the default profile) for ENGINI_API_TOKEN.`);
94
+ }
95
+ return clientFor({ token, companyToken: process.env.ENGINI_COMPANY_TOKEN }, profile.api_url);
96
+ }
97
+ if (profile.auth_kind === "oauth") {
98
+ if (process.env.ENGINI_COMPANY_TOKEN) {
99
+ fail(
100
+ 2 /* USAGE */,
101
+ `Profile "${active.name}" is a browser login, and ENGINI_COMPANY_TOKEN is set.`,
102
+ "Unset ENGINI_COMPANY_TOKEN: a browser login already names its account."
103
+ );
104
+ }
105
+ if (!profile.access_token) {
106
+ fail(3 /* AUTH */, `Profile "${active.name}" has no session.`, `Run \`engini login --profile ${active.name}\`.`);
107
+ }
108
+ return clientFor({ token: profile.access_token }, profile.api_url, pair);
477
109
  }
478
- const token = overrides.apiToken ?? process.env[ENV_TOKEN_VAR] ?? config.api_token;
479
- const company = overrides.companyToken ?? process.env[ENV_COMPANY_TOKEN_VAR] ?? config.company_token;
480
- if (!token) {
481
- fail(3 /* AUTH */, "No credentials found. Run `engini login`.");
110
+ if (profile.api_key) return clientFor({ apiKey: profile.api_key }, profile.api_url);
111
+ if (profile.api_token) {
112
+ if (!profile.company_token && process.env.ENGINI_COMPANY_TOKEN) {
113
+ fail(
114
+ 2 /* USAGE */,
115
+ `Profile "${active.name}" has a token but no company token, and ENGINI_COMPANY_TOKEN is set.`,
116
+ "Unset ENGINI_COMPANY_TOKEN, or log in again with the profile's own company token."
117
+ );
118
+ }
119
+ return clientFor({ token: profile.api_token, companyToken: profile.company_token }, profile.api_url);
482
120
  }
483
- return new Engini({
484
- token,
485
- companyToken: company,
486
- baseUrl: config.api_url,
487
- userAgentPrefix: USER_AGENT_PREFIX
488
- });
121
+ if (active.name !== void 0) {
122
+ fail(3 /* AUTH */, `Profile "${active.name}" has no credentials.`, `Run \`engini login --profile ${active.name}\`.`);
123
+ }
124
+ fail(3 /* AUTH */, "No credentials found. Run `engini login`.");
489
125
  }
490
126
  var AUTH_PROVIDER_CONFLICT_CODES = /* @__PURE__ */ new Set([
491
127
  "AUTH_PROVIDER_IN_USE",
@@ -522,7 +158,15 @@ async function apiErrors(fn) {
522
158
  return await fn();
523
159
  } catch (err) {
524
160
  if (err instanceof EnginiBuilderError) {
525
- fail(exitForError(err), err.message, err.fix ?? void 0, {
161
+ if (err.code === "API_KEY_REQUIRED") {
162
+ if (activeOAuthProfile() !== void 0) {
163
+ fail(exitForError(err), "This command needs an API-key profile.", KEY_PROFILE_HINT, {
164
+ code: err.code
165
+ });
166
+ }
167
+ }
168
+ const fix = err.code === "SCOPE_NOT_ACCESSIBLE" ? err.fix ?? "Run `engini whoami` to list the workspaces and environments you can open." : err.fix ?? void 0;
169
+ fail(exitForError(err), err.message, fix, {
526
170
  code: err.code,
527
171
  path: err.path,
528
172
  currentRevisionId: err.currentRevisionId,
@@ -533,11 +177,25 @@ async function apiErrors(fn) {
533
177
  fail(exitForError(err), err.message, SCOPE_READ_ONLY_HINT);
534
178
  }
535
179
  if (err instanceof EnginiError) {
180
+ const code = err.errorCode;
181
+ if (code === "CLI_TOKEN_NOT_ALLOWED") {
182
+ fail(exitForError(err), err.message, KEY_PROFILE_HINT);
183
+ }
536
184
  fail(exitForError(err), err.message);
537
185
  }
538
186
  throw err;
539
187
  }
540
188
  }
189
+ var KEY_PROFILE_HINT = "Save an API key in its own profile: engini login key --profile <name>, then pass --profile <name>.";
190
+ function activeOAuthProfile() {
191
+ try {
192
+ const active = resolveActive();
193
+ if (active.source === "env-credential" || active.profile.auth_kind !== "oauth") return void 0;
194
+ return active.name;
195
+ } catch {
196
+ return void 0;
197
+ }
198
+ }
541
199
 
542
200
  // src/tools/render.ts
543
201
  function clean(value) {
@@ -763,12 +421,12 @@ async function pollSignInStatus(client, state, opts) {
763
421
 
764
422
  // src/connect.ts
765
423
  var PLACEHOLDER = "<value>";
766
- function connectionsUrl(config) {
767
- return `${config.identity_url.replace(/\/+$/, "")}/connections#integrations`;
424
+ function connectionsUrl(identityUrl) {
425
+ return `${identityUrl.replace(/\/+$/, "")}/connections#integrations`;
768
426
  }
769
427
  async function connectBody(application, opts) {
770
428
  if (!application && opts.connection === void 0) {
771
- const url = connectionsUrl(loadConfig());
429
+ const url = connectionsUrl(resolveActive().profile.identity_url);
772
430
  openBrowser(url);
773
431
  printOutput({ url });
774
432
  return;
@@ -916,7 +574,7 @@ async function chooseAuth(methods, auth, application, provider) {
916
574
  need: "auth",
917
575
  application,
918
576
  methods: methods.map(methodSummary),
919
- resume: `engini connect ${application} --auth <id>${providerResumeFlag(provider)}`
577
+ resume: `engini connect ${application} --auth <id>${providerResumeFlag(provider)}${profileResumeFlag()}`
920
578
  });
921
579
  }
922
580
  async function collectFields(method, application, provided, oauthState, fieldOptions, provider, derived) {
@@ -935,7 +593,7 @@ async function collectFields(method, application, provided, oauthState, fieldOpt
935
593
  const schema = method.connectionFields.filter(
936
594
  (f) => !f.isHidden && !(providerPinned && f.setOnProvider)
937
595
  );
938
- const resumeHint = oauthState ? `Resume with: engini connect ${application} --auth ${method.authenticationId} --oauth-state ${oauthState}${providerResumeFlag(provider)}` : void 0;
596
+ const resumeHint = oauthState ? `Resume with: engini connect ${application} --auth ${method.authenticationId} --oauth-state ${oauthState}${providerResumeFlag(provider)}${profileResumeFlag()}` : void 0;
939
597
  for (const [k, v] of Object.entries(provided)) {
940
598
  if (v === PLACEHOLDER) delete provided[k];
941
599
  }
@@ -956,8 +614,8 @@ async function collectFields(method, application, provided, oauthState, fieldOpt
956
614
  }
957
615
  for (const k of derived ?? []) delete provided[k];
958
616
  const isSatisfied = (name) => name in provided || (derived?.has(name) ?? false);
959
- const required = schema.filter((f) => f.isRequired);
960
- const missing = required.filter((f) => !isSatisfied(f.fieldName));
617
+ const required2 = schema.filter((f) => f.isRequired);
618
+ const missing = required2.filter((f) => !isSatisfied(f.fieldName));
961
619
  if (missing.length === 0) return provided;
962
620
  if (isInteractive()) {
963
621
  for (const f of schema) {
@@ -975,6 +633,7 @@ async function collectFields(method, application, provided, oauthState, fieldOpt
975
633
  `--auth ${method.authenticationId}`,
976
634
  ...oauthState ? [`--oauth-state ${oauthState}`] : [],
977
635
  ...provider ? [`--provider ${provider.id}`] : [],
636
+ profileResumeFlag().trim(),
978
637
  fieldsFlags
979
638
  ].filter(Boolean);
980
639
  return need({
@@ -1034,7 +693,7 @@ async function resolveObjects(objs, connectionId, application) {
1034
693
  application,
1035
694
  connection_id: connectionId,
1036
695
  objects: objs.map(objectSummary),
1037
- resume: `engini connect ${app} --connection ${connectionId} --object <id>`
696
+ resume: `engini connect ${app} --connection ${connectionId} --object <id>${profileResumeFlag()}`
1038
697
  });
1039
698
  }
1040
699
  async function oauthFieldsFor(client, application, method, oauthState, field, timing, provider) {
@@ -1085,8 +744,9 @@ async function oauthFieldsFor(client, application, method, oauthState, field, ti
1085
744
  // The state pins the provider server-side, but the replay still needs it client-side to
1086
745
  // know which "Set on provider" fields not to ask for again.
1087
746
  ...provider ? [`--provider ${provider.id}`] : [],
747
+ profileResumeFlag().trim(),
1088
748
  ...(field ?? []).map((spec) => resumeFieldFlag(spec, secretFields))
1089
- ].join(" ")
749
+ ].filter(Boolean).join(" ")
1090
750
  });
1091
751
  }
1092
752
  function providerResumeFlag(provider) {
@@ -2045,7 +1705,7 @@ async function signInUrlBody(application, opts) {
2045
1705
  printOutput({
2046
1706
  sign_in_url: resp.signInUrl,
2047
1707
  state: resp.state,
2048
- resume: `engini connections oauth-complete ${application} --auth ${auth} --state ${resp.state}`
1708
+ resume: `engini connections oauth-complete ${application} --auth ${auth} --state ${resp.state}${profileResumeFlag()}`
2049
1709
  });
2050
1710
  }
2051
1711
  function registerConnectionsSignInUrl(connections) {
@@ -2200,12 +1860,36 @@ CORE COMMANDS
2200
1860
  Typical flow: login \u2192 applications list \u2192 tools list \u2192 tools call
2201
1861
 
2202
1862
  ACCOUNT
2203
- login Store an opaque Engini API key (eng_\u2026): --api-key, or interactive on a TTY.
2204
- The key must start with "eng_"; a malformed or empty one exits 2 and
2205
- stores nothing. Interactive entry needs a terminal on stdin AND stdout.
2206
- logout Clear the stored credentials.
2207
- whoami Show the authenticated user/company, and the workspace + environment an
2208
- API key is scoped to (both null for a login token or an unscoped key).
1863
+ login [--profile <name>] [--workspace <id> --environment <id>] [--no-browser]
1864
+ Sign in in the browser (default). Check that the confirmation code in the
1865
+ terminal matches the browser, then approve either everything you can open in
1866
+ the account (default) or one workspace + environment. The session refreshes
1867
+ itself for up to 30 days. --workspace/--environment set the profile's default
1868
+ pair. --no-browser prints the link instead (the link returns to 127.0.0.1 on
1869
+ the machine that opens it: over SSH, forward the port with ssh -L, or use
1870
+ \`login key\`). --auth-url <url> names the sign-in server (default: the API
1871
+ host with api. -> identity.); --allow-host <host> trusts one outside engini.io.
1872
+ login key [--profile <name>]
1873
+ Paste an API key (eng_\u2026) instead: interactive on a TTY, piped on stdin (CI),
1874
+ or --api-key. The key is checked with the server first; a malformed or empty
1875
+ one exits 2 and stores nothing. No terminal and no key: use this.
1876
+ logout Clear the selected profile's credentials (a browser login is also revoked).
1877
+ whoami Show the authenticated user/company, which profile answered, its scope mode
1878
+ (account | pair | key), the workspace + environment commands act in and
1879
+ every pair the login can open (accessible_scopes, with ids - names repeat).
1880
+ profile list | show [name] | add <name> | use <name> | rename <old> <new> | rm <name>
1881
+ Manage named logins - one per account or environment. Every command takes
1882
+ --profile <name>; \`profile use\` sets the default.
1883
+
1884
+ Workspace + environment (browser logins): every command takes --workspace <id>
1885
+ --environment <id> (GUIDs, always together; or ENGINI_WORKSPACE_ID +
1886
+ ENGINI_ENVIRONMENT_ID), else the profile's default pair. With none, lists cover every
1887
+ pair you can open, and a write exits 2 asking for one - it never lands silently in the
1888
+ account's default workspace. An API-key profile is pinned to its key's pair (naming
1889
+ one exits 2). The workflow builder (workflows search|schema|options|tables|columns|
1890
+ connections|compile|plan|create|update) works on both profile kinds; on a browser login
1891
+ its reads and writes both need a pair and exit 2 without one. Template submit needs an
1892
+ API-key profile.
2209
1893
 
2210
1894
  CONNECTIONS
2211
1895
  connect [<app>] [--provider <name|id|none>]
@@ -2401,15 +2085,31 @@ ${exitCodeLines()}
2401
2085
 
2402
2086
  FILES & ENVIRONMENT
2403
2087
  Config: $XDG_CONFIG_HOME/engini/config.toml (Windows: %APPDATA%\\engini\\config.toml)
2404
- Written 0600; stores api_url / identity_url / api_key / auth_kind.
2405
- Re-run \`engini login\` to change it.
2406
- Env: ENGINI_API_KEY (preferred) or ENGINI_API_TOKEN, plus ENGINI_COMPANY_TOKEN.
2407
- Resolution order: flags > environment > config.
2088
+ Written 0600; named profiles, each with api_url / identity_url / a credential (an
2089
+ API key, or a browser login's tokens + scope mode + default pair) and the company
2090
+ it belongs to. Upgrade every engini CLI on a machine together: older versions
2091
+ cannot read this file.
2092
+ Env: ENGINI_PROFILE picks a profile for one shell. ENGINI_API_TOKEN (+ ENGINI_COMPANY_TOKEN)
2093
+ is a credential for scripts. ENGINI_API_KEY is no longer read: set, every command
2094
+ exits 2 - save the key with \`printf %s "$KEY" | engini login key --profile ci\`.
2095
+ Profile order: --profile > ENGINI_PROFILE > ENGINI_API_TOKEN > default profile.
2096
+ ENGINI_PROFILE together with ENGINI_API_TOKEN exits 2; an unknown profile exits 4.
2097
+ ENGINI_WORKSPACE_ID + ENGINI_ENVIRONMENT_ID pick the pair for one shell (browser
2098
+ logins only; beside a key or ENGINI_API_TOKEN they exit 2).
2408
2099
  ENGINI_NO_UPDATE_CHECK=1 skips the "update available" check on a TTY.
2409
2100
 
2410
2101
  EXAMPLES
2411
- # Authenticate (or set ENGINI_API_KEY)
2412
- engini login --api-key eng_\u2026
2102
+ # Authenticate (a profile per account; the first one becomes the default)
2103
+ engini login # browser sign-in
2104
+ engini login --profile staging --api-url https://api.staging.engini.io
2105
+ printf %s "$KEY" | engini login key --profile ci # CI: an API key on stdin
2106
+
2107
+ # Act in one workspace + environment (browser logins; ids from \`engini whoami\`)
2108
+ engini workflows list --workspace <ws-id> --environment <env-id>
2109
+
2110
+ # Act as another profile for one command or one shell
2111
+ engini whoami --profile staging
2112
+ ENGINI_PROFILE=staging engini tools list
2413
2113
 
2414
2114
  # Discover apps and tools; pipe JSON to jq
2415
2115
  engini applications list --available --limit 10
@@ -2446,14 +2146,28 @@ LEARN MORE
2446
2146
  }
2447
2147
  var EXAMPLES = {
2448
2148
  login: `Examples:
2449
- engini login --api-key eng_\u2026 # store a key non-interactively
2450
- engini login --api-url https://staging.engini.io # point at another environment
2149
+ engini login # browser sign-in (default)
2150
+ engini login --profile staging --api-url https://api.staging.engini.io
2151
+ engini login --workspace <ws-id> --environment <env-id> # also store a default pair
2152
+ engini login --no-browser # print the link instead of opening it
2153
+ printf %s "$KEY" | engini login key --profile ci # CI: an API key on stdin, not the command line
2154
+ engini login key # paste an API key when prompted
2451
2155
  engini login --api-key eng_\u2026 --dry-run # preview without writing
2452
- engini login # interactive: paste the key when prompted
2453
2156
 
2454
- The key must start with "eng_". A malformed or empty key exits 2 without writing
2455
- anything, on either path. Interactive entry needs a terminal on both stdin and
2456
- stdout \u2014 pipe stdin (e.g. in CI) and you must pass --api-key.`,
2157
+ Browser login: compare the confirmation code shown here with the one in the browser,
2158
+ then approve everything you can open in the account (default) or one workspace +
2159
+ environment. The session refreshes itself for up to 30 days; \`engini logout\` revokes
2160
+ it. Browser login needs a terminal (or --no-browser); without either, paste a key.
2161
+ Over SSH the sign-in link returns to 127.0.0.1 on the machine that opens it: forward
2162
+ the port the CLI prints (ssh -L) or use \`login key\`. Builder commands
2163
+ (\`engini workflows search|schema|...|create|update\`) work on a browser login too, in
2164
+ the one workspace + environment you name (--workspace/--environment, env vars or the
2165
+ profile's default). Template submit needs an API-key profile.
2166
+
2167
+ API key: it must start with "eng_". A malformed or empty key exits 2 without writing
2168
+ anything, on every path. It is checked with the server before it is stored (a
2169
+ rejected key exits 3). --expect-company <name> refuses a login that belongs to
2170
+ another company (exit 5).`,
2457
2171
  "tools list": `Examples:
2458
2172
  engini tools list --application monday --limit 5
2459
2173
  engini tools list | jq -r '.[].tool_slug'
@@ -2512,8 +2226,213 @@ function installHelp(program) {
2512
2226
  }
2513
2227
 
2514
2228
  // src/login.ts
2515
- function keysUrl(config) {
2516
- return `${config.identity_url.replace(/\/+$/, "")}/api-keys`;
2229
+ import { Option } from "commander";
2230
+ import { EnginiAuthError as EnginiAuthError2 } from "@engini/sdk";
2231
+
2232
+ // src/oauth-login.ts
2233
+ import { createHash, randomBytes, timingSafeEqual } from "crypto";
2234
+ import { createServer } from "http";
2235
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "[::1]"]);
2236
+ var TOKEN_TIMEOUT_MS = 3e4;
2237
+ var PROBE_TIMEOUT_MS = 15e3;
2238
+ function base32(bytes) {
2239
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
2240
+ let bits = 0;
2241
+ let value = 0;
2242
+ let out = "";
2243
+ for (const byte of bytes) {
2244
+ value = value << 8 | byte;
2245
+ bits += 8;
2246
+ while (bits >= 5) {
2247
+ out += alphabet[value >>> bits - 5 & 31];
2248
+ bits -= 5;
2249
+ }
2250
+ }
2251
+ if (bits > 0) out += alphabet[value << 5 - bits & 31];
2252
+ return out;
2253
+ }
2254
+ function confirmationCode(codeChallenge) {
2255
+ return base32(createHash("sha256").update(codeChallenge, "utf8").digest()).slice(0, 6);
2256
+ }
2257
+ function checkAuthUrl(authUrl, allowHost) {
2258
+ let url;
2259
+ try {
2260
+ url = new URL(authUrl);
2261
+ } catch {
2262
+ fail(2 /* USAGE */, `--auth-url is not a URL: "${authUrl}".`);
2263
+ }
2264
+ const host = url.hostname.toLowerCase();
2265
+ const loopback = LOOPBACK_HOSTS.has(host);
2266
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
2267
+ fail(2 /* USAGE */, `The sign-in server must use https (got ${url.protocol}//${url.host}).`);
2268
+ }
2269
+ const engini = host === "engini.io" || host.endsWith(".engini.io");
2270
+ if (!engini && host !== allowHost?.trim().toLowerCase()) {
2271
+ fail(
2272
+ 2 /* USAGE */,
2273
+ `Refusing to sign in at ${url.host}: not an engini.io host.`,
2274
+ `If you trust it, pass --allow-host ${url.hostname}.`
2275
+ );
2276
+ }
2277
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
2278
+ }
2279
+ async function probe(authUrl) {
2280
+ const noBrowserLogin = () => fail(3 /* AUTH */, "This server has no browser login yet - run engini login key.", "Paste an API key instead: engini login key");
2281
+ let res;
2282
+ try {
2283
+ res = await fetch(`${authUrl}/api/oauth/clients/${CLIENT_ID}/public-info`, {
2284
+ headers: { accept: "application/json" },
2285
+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS)
2286
+ });
2287
+ } catch (err) {
2288
+ fail(
2289
+ 1 /* GENERIC */,
2290
+ `Cannot reach the sign-in server at ${authUrl}: ${err instanceof Error ? err.message : String(err)}`,
2291
+ "Check --auth-url / --api-url and your network, or paste an API key: engini login key"
2292
+ );
2293
+ }
2294
+ if (!res.ok) noBrowserLogin();
2295
+ let info;
2296
+ try {
2297
+ info = await res.json();
2298
+ } catch {
2299
+ return noBrowserLogin();
2300
+ }
2301
+ if (info.nativeLoopback !== true) noBrowserLogin();
2302
+ return { sessionLifetimeDays: typeof info.sessionLifetimeDays === "number" ? info.sessionLifetimeDays : void 0 };
2303
+ }
2304
+ async function listenLoopback() {
2305
+ for (let attempt = 0; attempt < 5; attempt++) {
2306
+ const server = createServer();
2307
+ await new Promise((resolve, reject) => {
2308
+ server.once("error", reject);
2309
+ server.listen(0, "127.0.0.1", () => resolve());
2310
+ });
2311
+ const { port } = server.address();
2312
+ if (port >= 1024) return { server, port };
2313
+ await new Promise((resolve) => server.close(() => resolve()));
2314
+ }
2315
+ fail(1 /* GENERIC */, "Could not open a local port (>= 1024) for the sign-in callback.");
2316
+ }
2317
+ var PAGE_HEADERS = {
2318
+ "content-type": "text/html; charset=utf-8",
2319
+ "cache-control": "no-store",
2320
+ "referrer-policy": "no-referrer"
2321
+ };
2322
+ function page(res, status, text) {
2323
+ res.writeHead(status, PAGE_HEADERS);
2324
+ res.end(
2325
+ `<!doctype html><html><head><meta charset="utf-8"><title>Engini CLI</title></head><body style="font-family:system-ui,sans-serif;margin:3rem"><p>${text}</p></body></html>`
2326
+ );
2327
+ }
2328
+ function safeEqual(a, b) {
2329
+ const x = Buffer.from(a, "utf8");
2330
+ const y = Buffer.from(b, "utf8");
2331
+ return x.length === y.length && timingSafeEqual(x, y);
2332
+ }
2333
+ function waitForCallback(server, port, state, timeoutSec) {
2334
+ return new Promise((resolve) => {
2335
+ const timer = setTimeout(() => resolve("timeout"), timeoutSec * 1e3);
2336
+ server.on("request", (req, res) => {
2337
+ const url = new URL(req.url ?? "/", `http://127.0.0.1:${port}`);
2338
+ const ok = req.method === "GET" && url.pathname === "/callback" && req.headers.host === `127.0.0.1:${port}` && safeEqual(url.searchParams.get("state") ?? "", state);
2339
+ if (!ok) {
2340
+ page(res, 404, "Not found.");
2341
+ return;
2342
+ }
2343
+ clearTimeout(timer);
2344
+ const error = url.searchParams.get("error");
2345
+ const code = url.searchParams.get("code");
2346
+ if (error || !code) {
2347
+ page(res, 200, "Sign-in was not completed. You can close this tab and return to the terminal.");
2348
+ resolve({ error: error ?? "no_code" });
2349
+ return;
2350
+ }
2351
+ page(res, 200, "Signed in. You can close this tab and return to the terminal.");
2352
+ resolve({ code });
2353
+ });
2354
+ });
2355
+ }
2356
+ async function exchange(authUrl, code, redirectUri, verifier) {
2357
+ let res;
2358
+ try {
2359
+ res = await fetch(`${authUrl}/api/oauth/token`, {
2360
+ method: "POST",
2361
+ // The token endpoint binds form fields only ([FromForm]); JSON is refused.
2362
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
2363
+ body: new URLSearchParams({
2364
+ grant_type: "authorization_code",
2365
+ code,
2366
+ redirect_uri: redirectUri,
2367
+ client_id: CLIENT_ID,
2368
+ code_verifier: verifier
2369
+ }).toString(),
2370
+ signal: AbortSignal.timeout(TOKEN_TIMEOUT_MS)
2371
+ });
2372
+ } catch (err) {
2373
+ fail(1 /* GENERIC */, `Could not finish signing in: ${err instanceof Error ? err.message : String(err)}`, "Run engini login again.");
2374
+ }
2375
+ if (res.status === 400) fail(3 /* AUTH */, "The sign-in server refused the login code.", "Run engini login again.");
2376
+ if (res.status === 429) fail(1 /* GENERIC */, "The sign-in server is rate limiting.", "Retry shortly.");
2377
+ if (!res.ok) fail(1 /* GENERIC */, `The sign-in server answered ${res.status}.`, "Run engini login again.");
2378
+ let body;
2379
+ try {
2380
+ body = await res.json();
2381
+ } catch {
2382
+ fail(1 /* GENERIC */, "The sign-in server sent an unreadable token response.");
2383
+ }
2384
+ if (typeof body.access_token !== "string" || typeof body.refresh_token !== "string" || typeof body.expires_in !== "number") {
2385
+ fail(1 /* GENERIC */, "The sign-in server sent an incomplete token response.");
2386
+ }
2387
+ return {
2388
+ accessToken: body.access_token,
2389
+ refreshToken: body.refresh_token,
2390
+ expiresIn: body.expires_in,
2391
+ scopeMode: typeof body.scope_mode === "string" ? body.scope_mode : void 0
2392
+ };
2393
+ }
2394
+ async function oauthLogin(opts) {
2395
+ const authUrl = checkAuthUrl(opts.authUrl, opts.allowHost);
2396
+ const { sessionLifetimeDays } = await probe(authUrl);
2397
+ const verifier = randomBytes(32).toString("base64url");
2398
+ const challenge = createHash("sha256").update(verifier, "ascii").digest("base64url");
2399
+ const state = randomBytes(16).toString("base64url");
2400
+ const { server, port } = await listenLoopback();
2401
+ try {
2402
+ const redirectUri = `http://127.0.0.1:${port}/callback`;
2403
+ const link = `${authUrl}/oauth/authorize?response_type=code&client_id=${encodeURIComponent(CLIENT_ID)}&redirect_uri=${encodeURIComponent(redirectUri)}&code_challenge=${encodeURIComponent(challenge)}&code_challenge_method=S256&state=${encodeURIComponent(state)}&scope=${encodeURIComponent("openid profile")}`;
2404
+ console.error(`Sign in to Engini in your browser:
2405
+ ${link}`);
2406
+ console.error(`Confirmation code: ${confirmationCode(challenge)} (the browser shows the same code)`);
2407
+ if (opts.openBrowser) {
2408
+ opts.opener?.(link);
2409
+ } else {
2410
+ console.error(
2411
+ `The link redirects to 127.0.0.1:${port} on the machine that opens it. On a remote shell, forward the port first: ssh -L ${port}:127.0.0.1:${port} <host>. No browser at all? Use engini login key.`
2412
+ );
2413
+ }
2414
+ const outcome = await waitForCallback(server, port, state, opts.timeoutSec);
2415
+ if (outcome === "timeout") {
2416
+ fail(124 /* TIMEOUT */, `No sign-in arrived within ${opts.timeoutSec} s.`, "Run engini login again (or --timeout <sec>).");
2417
+ }
2418
+ if ("error" in outcome) {
2419
+ if (outcome.error === "access_denied") fail(3 /* AUTH */, "Sign-in was declined in the browser.");
2420
+ const reason = outcome.error.replace(/[^\w.-]/g, "").slice(0, 64) || "unknown";
2421
+ fail(3 /* AUTH */, `Sign-in failed in the browser (${reason}).`, "Run engini login again.");
2422
+ }
2423
+ const tokens = await exchange(authUrl, outcome.code, redirectUri, verifier);
2424
+ return { ...tokens, sessionLifetimeDays };
2425
+ } finally {
2426
+ server.closeAllConnections();
2427
+ await new Promise((resolve) => server.close(() => resolve()));
2428
+ }
2429
+ }
2430
+
2431
+ // src/login.ts
2432
+ var DEFAULT_TIMEOUT_SEC = 300;
2433
+ var DEFAULT_SESSION_DAYS = 30;
2434
+ function keysUrl(identityUrl) {
2435
+ return `${identityUrl.replace(/\/+$/, "")}/api-keys`;
2517
2436
  }
2518
2437
  var MAX_KEY_ATTEMPTS = 3;
2519
2438
  function charCount(key) {
@@ -2527,6 +2446,7 @@ function keyProblem(key, truncated = false) {
2527
2446
  }
2528
2447
  return null;
2529
2448
  }
2449
+ var STDIN_HINT = 'Pipe it on stdin: printf %s "$KEY" | engini login key';
2530
2450
  async function askForKey(url) {
2531
2451
  console.log("");
2532
2452
  console.log("Paste your API key below - it will not be echoed.");
@@ -2538,19 +2458,15 @@ async function askForKey(url) {
2538
2458
  try {
2539
2459
  ({ value: key, truncated } = await promptHidden(" API key"));
2540
2460
  } catch (err) {
2541
- if (err instanceof PromptCancelled) fail(2 /* USAGE */, "Cancelled \u2014 no credentials stored.");
2461
+ if (err instanceof PromptCancelled) fail(2 /* USAGE */, "Cancelled - no credentials stored.");
2542
2462
  if (err instanceof PromptStreamEnded) {
2543
- fail(
2544
- 2 /* USAGE */,
2545
- "Input ended before a key was entered.",
2546
- "Pass the key directly instead: engini login --api-key eng_\u2026"
2547
- );
2463
+ fail(2 /* USAGE */, "Input ended before a key was entered.", STDIN_HINT);
2548
2464
  }
2549
2465
  throw err;
2550
2466
  }
2551
2467
  const problem = keyProblem(key, truncated);
2552
2468
  if (!problem) {
2553
- console.log(` \u2713 Received ${charCount(key)} characters \u2014 ${maskSecret(key)}`);
2469
+ console.log(` \u2713 Received ${charCount(key)} characters - ${maskSecret(key)}`);
2554
2470
  console.log("");
2555
2471
  return key;
2556
2472
  }
@@ -2558,18 +2474,68 @@ async function askForKey(url) {
2558
2474
  fail(
2559
2475
  2 /* USAGE */,
2560
2476
  `${problem} Giving up after ${MAX_KEY_ATTEMPTS} attempts.`,
2561
- `Pass the key directly instead: engini login --api-key eng_\u2026 (create one at ${url})`
2477
+ `${STDIN_HINT} (create a key at ${url})`
2562
2478
  );
2563
2479
  }
2564
2480
  console.log(` ! ${problem} Try again, or press Ctrl-C to cancel.`);
2565
2481
  console.log("");
2566
2482
  }
2567
2483
  }
2568
- async function loginBody(opts) {
2569
- const config = loadConfig();
2570
- const hadCredentials = Boolean(config.api_key || config.api_token);
2571
- if (opts.apiUrl) config.api_url = opts.apiUrl;
2572
- if (opts.identityUrl) config.identity_url = opts.identityUrl;
2484
+ async function keyFromStdin() {
2485
+ const raw = (await readStdin()).trim();
2486
+ const multiline = raw.includes("\n");
2487
+ const problem = keyProblem(multiline ? raw.split("\n")[0].trim() : raw, multiline);
2488
+ if (problem) fail(2 /* USAGE */, `The key on stdin is not usable. ${problem}`, STDIN_HINT);
2489
+ return raw;
2490
+ }
2491
+ function sameCompany(a, b) {
2492
+ return a.trim().toLowerCase() === b.trim().toLowerCase();
2493
+ }
2494
+ async function loginBody(method, opts, target) {
2495
+ if (method !== void 0 && method !== "key") {
2496
+ fail(
2497
+ 2 /* USAGE */,
2498
+ `Unknown login method "${method}".`,
2499
+ "Run `engini login` (browser sign-in) or `engini login key` (paste an API key)."
2500
+ );
2501
+ }
2502
+ if (method === "key" && opts.apiKey !== void 0) {
2503
+ fail(2 /* USAGE */, "Pass the key either as `login key` (stdin or prompt) or with --api-key, not both.");
2504
+ }
2505
+ if (method === "key" || opts.apiKey !== void 0) {
2506
+ const browserOnly = [
2507
+ [opts.browser === false, "--no-browser"],
2508
+ [opts.timeout !== void 0, "--timeout"],
2509
+ [opts.authUrl !== void 0, "--auth-url"],
2510
+ [opts.allowHost !== void 0, "--allow-host"],
2511
+ [opts.workspace !== void 0 || opts.environment !== void 0, "--workspace/--environment"]
2512
+ ];
2513
+ const misplaced = browserOnly.filter(([given]) => given).map(([, flag]) => flag);
2514
+ if (misplaced.length > 0) {
2515
+ fail(
2516
+ 2 /* USAGE */,
2517
+ `${misplaced.join(", ")} ${misplaced.length === 1 ? "applies" : "apply"} to the browser login only.`,
2518
+ "Drop them, or run `engini login` without `key` / --api-key."
2519
+ );
2520
+ }
2521
+ return pasteLogin(method, opts, target);
2522
+ }
2523
+ return browserLogin(opts, target);
2524
+ }
2525
+ async function pasteLogin(method, opts, target) {
2526
+ const existing = getProfile(loadConfig(), target.name);
2527
+ if (target.refuseExisting && existing) {
2528
+ fail(
2529
+ 5 /* VALIDATION */,
2530
+ `Profile "${target.name}" already exists.`,
2531
+ `Replace its login with \`engini login --profile ${target.name}\`.`
2532
+ );
2533
+ }
2534
+ const hadCredentials = Boolean(
2535
+ existing?.api_key || existing?.api_token || existing?.access_token || existing?.refresh_token || existing?.auth_kind === "oauth"
2536
+ );
2537
+ const apiUrl = opts.apiUrl ?? existing?.api_url ?? profileDefaults().api_url;
2538
+ const identityUrl = resolveIdentityUrl(opts, existing, apiUrl);
2573
2539
  let apiKey = opts.apiKey?.trim();
2574
2540
  if (opts.apiKey !== void 0) {
2575
2541
  const problem = keyProblem(apiKey ?? "");
@@ -2581,87 +2547,426 @@ async function loginBody(opts) {
2581
2547
  );
2582
2548
  }
2583
2549
  }
2550
+ if (!apiKey && method === "key" && !process.stdin.isTTY) apiKey = await keyFromStdin();
2584
2551
  if (!apiKey) {
2585
2552
  if (!isInteractive()) {
2586
2553
  fail(
2587
2554
  2 /* USAGE */,
2588
- "Provide --api-key when running non-interactively.",
2589
- "Interactive login needs a terminal on both stdin and stdout."
2555
+ "Provide the key when running non-interactively.",
2556
+ `${STDIN_HINT} (or pass --api-key). Interactive login needs a terminal on both stdin and stdout.`
2590
2557
  );
2591
2558
  }
2592
- const url = keysUrl(config);
2559
+ const url = keysUrl(identityUrl);
2593
2560
  let hasKey;
2594
2561
  try {
2595
2562
  hasKey = await confirm("Do you already have an Engini API key?");
2596
2563
  } catch (err) {
2597
2564
  if (err instanceof PromptStreamEnded) {
2598
- fail(
2599
- 2 /* USAGE */,
2600
- "Input ended before the question was answered.",
2601
- "Pass the key directly instead: engini login --api-key eng_\u2026"
2602
- );
2565
+ fail(2 /* USAGE */, "Input ended before the question was answered.", STDIN_HINT);
2603
2566
  }
2604
2567
  throw err;
2605
2568
  }
2606
- if (!hasKey) {
2607
- console.log(`Opening ${url} \u2014 create a key there, then paste it below.`);
2569
+ if (!hasKey && !dryRun()) {
2570
+ console.log(`Opening ${url} - create a key there, then paste it below.`);
2608
2571
  openBrowser(url);
2609
2572
  }
2610
2573
  apiKey = await askForKey(url);
2611
2574
  }
2612
- config.api_key = apiKey;
2613
- config.auth_kind = "api-key";
2614
2575
  const summary6 = {
2576
+ profile: target.name,
2615
2577
  auth_kind: "api-key",
2616
2578
  credential: maskSecret(apiKey),
2617
- api_url: config.api_url
2579
+ api_url: apiUrl
2618
2580
  };
2619
2581
  if (dryRun()) {
2620
2582
  printOutput({ would_store: summary6 });
2621
2583
  return;
2622
2584
  }
2623
2585
  if (hadCredentials) {
2624
- await confirmOrFail("Credentials already exist. Overwrite?", { force: Boolean(opts.force) });
2586
+ await confirmOrFail(`Profile "${target.name}" already has credentials. Overwrite?`, {
2587
+ force: Boolean(opts.force)
2588
+ });
2589
+ }
2590
+ let labels = {};
2591
+ try {
2592
+ const me = await clientFor({ apiKey }, apiUrl).auth.whoami();
2593
+ labels = {
2594
+ company: me.currentCompany ?? void 0,
2595
+ workspace: me.workspace?.name ?? void 0,
2596
+ environment: me.environment?.name ?? void 0
2597
+ };
2598
+ } catch (err) {
2599
+ if (err instanceof EnginiAuthError2) {
2600
+ fail(3 /* AUTH */, "The server rejected that key (401). Nothing was stored.", "Check the key and --api-url, then try again.");
2601
+ }
2602
+ if (opts.expectCompany !== void 0) {
2603
+ fail(1 /* GENERIC */, "Could not verify the key's company before storing it, so --expect-company cannot be honored.");
2604
+ }
2605
+ note("Could not reach the server to check the key; stored it without account labels.");
2606
+ }
2607
+ if (opts.expectCompany !== void 0 && !sameCompany(labels.company ?? "", opts.expectCompany)) {
2608
+ fail(
2609
+ 5 /* VALIDATION */,
2610
+ `This key belongs to "${labels.company ?? "an unknown company"}", not "${opts.expectCompany}". Nothing was stored.`
2611
+ );
2612
+ }
2613
+ let isDefault = false;
2614
+ let previous;
2615
+ await withRefreshLock(
2616
+ target.name,
2617
+ () => updateConfig((fresh) => {
2618
+ const base = getProfile(fresh, target.name);
2619
+ if (target.refuseExisting && base) {
2620
+ fail(5 /* VALIDATION */, `Profile "${target.name}" already exists.`);
2621
+ }
2622
+ previous = oauthSessionOf(base);
2623
+ const next = { ...profileDefaults(), ...base, api_url: apiUrl, identity_url: identityUrl };
2624
+ clearOAuth(next);
2625
+ next.api_key = apiKey;
2626
+ next.auth_kind = "api-key";
2627
+ next.api_token = void 0;
2628
+ next.company_token = void 0;
2629
+ next.login_method = "key";
2630
+ next.company = labels.company;
2631
+ next.workspace = labels.workspace;
2632
+ next.environment = labels.environment;
2633
+ if (opts.description !== void 0) next.description = opts.description;
2634
+ fresh.profiles[target.name] = next;
2635
+ isDefault = claimDefault(fresh, target.name);
2636
+ })
2637
+ );
2638
+ if (previous) await revokePrevious(previous);
2639
+ printOutput({
2640
+ stored: {
2641
+ ...summary6,
2642
+ default: isDefault,
2643
+ company: labels.company ?? null,
2644
+ workspace: labels.workspace ?? null,
2645
+ environment: labels.environment ?? null
2646
+ }
2647
+ });
2648
+ }
2649
+ function oauthSessionOf(profile) {
2650
+ return profile?.auth_kind === "oauth" && profile.refresh_token ? { auth_url: profile.auth_url, refresh_token: profile.refresh_token } : void 0;
2651
+ }
2652
+ function clearOAuth(profile) {
2653
+ for (const key of OAUTH_FIELDS) profile[key] = void 0;
2654
+ }
2655
+ function claimDefault(config, name) {
2656
+ if (config.default_profile === void 0 || !Object.hasOwn(config.profiles, config.default_profile)) {
2657
+ config.default_profile = name;
2658
+ }
2659
+ return config.default_profile === name;
2660
+ }
2661
+ async function revokePrevious(previous) {
2662
+ if (!await revokeSession(previous)) {
2663
+ note("Could not revoke the profile's previous browser session; it ends on its own within 30 days.");
2664
+ }
2665
+ }
2666
+ function deriveAuthUrl(apiUrl) {
2667
+ let url;
2668
+ try {
2669
+ url = new URL(apiUrl);
2670
+ } catch {
2671
+ fail(2 /* USAGE */, `--api-url is not a URL: "${apiUrl}".`);
2672
+ }
2673
+ if (!url.hostname.startsWith("api.")) {
2674
+ fail(
2675
+ 2 /* USAGE */,
2676
+ `Cannot tell the sign-in server for ${url.host}.`,
2677
+ "Pass --auth-url <identity host>, e.g. --auth-url https://identity.engini.io"
2678
+ );
2679
+ }
2680
+ url.hostname = `identity.${url.hostname.slice("api.".length)}`;
2681
+ return url.origin;
2682
+ }
2683
+ function hostOf(url) {
2684
+ try {
2685
+ return url === void 0 ? void 0 : new URL(url).host;
2686
+ } catch {
2687
+ return void 0;
2688
+ }
2689
+ }
2690
+ function resolveIdentityUrl(opts, existing, apiUrl) {
2691
+ if (opts.identityUrl !== void 0) return opts.identityUrl;
2692
+ const apiHostChanged = opts.apiUrl !== void 0 && hostOf(opts.apiUrl) !== hostOf(existing?.api_url);
2693
+ if (existing?.identity_url && !apiHostChanged) return existing.identity_url;
2694
+ let url;
2695
+ try {
2696
+ url = new URL(apiUrl);
2697
+ } catch {
2698
+ }
2699
+ if (url?.hostname.startsWith("api.")) {
2700
+ url.hostname = `app.${url.hostname.slice("api.".length)}`;
2701
+ return url.origin;
2702
+ }
2703
+ note(
2704
+ `Could not derive the app URL for ${url?.host ?? apiUrl}; links (keys page, connections) point to ${profileDefaults().identity_url}. Pass --identity-url <app url> to change it.`
2705
+ );
2706
+ return profileDefaults().identity_url;
2707
+ }
2708
+ function parseTimeout(value) {
2709
+ if (value === void 0) return DEFAULT_TIMEOUT_SEC;
2710
+ const n = Number(value);
2711
+ if (!/^\d+$/.test(value.trim()) || n < 1 || n > 3600) {
2712
+ fail(2 /* USAGE */, `--timeout must be a whole number of seconds between 1 and 3600, got "${value}".`);
2713
+ }
2714
+ return n;
2715
+ }
2716
+ function pairLabels(row2) {
2717
+ return { workspace: row2?.workspace.name ?? void 0, environment: row2?.environment.name ?? void 0 };
2718
+ }
2719
+ async function browserLogin(opts, target) {
2720
+ const named = checkedPair(opts.workspace, opts.environment, ["--workspace", "--environment"]);
2721
+ const timeoutSec = parseTimeout(opts.timeout);
2722
+ const existing = getProfile(loadConfig(), target.name);
2723
+ if (target.refuseExisting && existing) {
2724
+ fail(
2725
+ 5 /* VALIDATION */,
2726
+ `Profile "${target.name}" already exists.`,
2727
+ `Replace its login with \`engini login --profile ${target.name}\`.`
2728
+ );
2729
+ }
2730
+ if (opts.authUrl !== void 0 && opts.apiUrl === void 0 && !existing) {
2731
+ fail(
2732
+ 2 /* USAGE */,
2733
+ "--auth-url on a new profile needs --api-url too, or the API host would default to production.",
2734
+ "Pass both, e.g. --api-url https://api.staging.engini.io --auth-url https://identity.staging.engini.io"
2735
+ );
2736
+ }
2737
+ const apiUrl = opts.apiUrl ?? existing?.api_url ?? profileDefaults().api_url;
2738
+ const identityUrl = resolveIdentityUrl(opts, existing, apiUrl);
2739
+ const storedAuthUrl = opts.apiUrl === void 0 || opts.apiUrl === existing?.api_url ? existing?.auth_url : void 0;
2740
+ const authUrl = checkAuthUrl(opts.authUrl ?? storedAuthUrl ?? deriveAuthUrl(apiUrl), opts.allowHost);
2741
+ if (opts.browser !== false && !isInteractive()) {
2742
+ fail(
2743
+ 2 /* USAGE */,
2744
+ "Browser login needs a terminal.",
2745
+ 'Without one, save an API key: printf %s "$KEY" | engini login key (or --api-key). To print the sign-in link instead of opening a browser, pass --no-browser.'
2746
+ );
2747
+ }
2748
+ const hadCredentials = Boolean(
2749
+ existing?.api_key || existing?.api_token || existing?.access_token || existing?.refresh_token || existing?.auth_kind === "oauth"
2750
+ );
2751
+ const summary6 = {
2752
+ profile: target.name,
2753
+ auth_kind: "oauth",
2754
+ api_url: apiUrl,
2755
+ auth_url: authUrl
2756
+ };
2757
+ if (dryRun()) {
2758
+ printOutput({
2759
+ would_store: {
2760
+ ...summary6,
2761
+ workspace_id: named?.workspaceId ?? null,
2762
+ environment_id: named?.environmentId ?? null
2763
+ }
2764
+ });
2765
+ return;
2766
+ }
2767
+ if (hadCredentials) {
2768
+ await confirmOrFail(`Profile "${target.name}" already has credentials. Overwrite?`, {
2769
+ force: Boolean(opts.force)
2770
+ });
2771
+ }
2772
+ const session = await oauthLogin({
2773
+ authUrl,
2774
+ allowHost: opts.allowHost,
2775
+ openBrowser: opts.browser !== false,
2776
+ timeoutSec,
2777
+ opener: (url) => {
2778
+ openBrowser(url);
2779
+ }
2780
+ });
2781
+ const newSession = { auth_url: authUrl, refresh_token: session.refreshToken };
2782
+ let stored;
2783
+ let previous;
2784
+ try {
2785
+ const scopeMode = session.scopeMode;
2786
+ if (scopeMode !== "account" && scopeMode !== "pair") {
2787
+ fail(3 /* AUTH */, "This sign-in server is too old for browser login.", "Paste an API key instead: engini login key");
2788
+ }
2789
+ let me;
2790
+ try {
2791
+ me = await clientFor({ token: session.accessToken }, apiUrl).auth.whoami();
2792
+ } catch (err) {
2793
+ if (err instanceof EnginiAuthError2) {
2794
+ fail(3 /* AUTH */, "The API rejected the new sign-in (401/403). Nothing was stored.", "Check --api-url, then try again.");
2795
+ }
2796
+ if (opts.expectCompany !== void 0 || named !== void 0) {
2797
+ fail(1 /* GENERIC */, "Could not reach the API to check the sign-in, so --expect-company / --workspace cannot be honored.");
2798
+ }
2799
+ note("Could not reach the API to check the sign-in; stored it without account labels or a default pair.");
2800
+ }
2801
+ const company = me?.currentCompany ?? void 0;
2802
+ if (opts.expectCompany !== void 0 && !sameCompany(company ?? "", opts.expectCompany)) {
2803
+ fail(
2804
+ 5 /* VALIDATION */,
2805
+ `This sign-in is for "${company ?? "an unknown company"}", not "${opts.expectCompany}". Nothing was stored.`
2806
+ );
2807
+ }
2808
+ const rows = flattenScopes(me?.accessibleScopes);
2809
+ let pair;
2810
+ let row2;
2811
+ if (named) {
2812
+ row2 = findScope(rows, named);
2813
+ if (!row2) {
2814
+ fail(
2815
+ 5 /* VALIDATION */,
2816
+ `${named.workspaceId}/${named.environmentId} is not a workspace/environment this sign-in can open. Nothing was stored.`,
2817
+ "Run without --workspace/--environment, then `engini whoami` lists the pairs you can open."
2818
+ );
2819
+ }
2820
+ pair = named;
2821
+ } else if (rows.length === 1) {
2822
+ row2 = rows[0];
2823
+ pair = { workspaceId: row2.workspace.id, environmentId: row2.environment.id };
2824
+ }
2825
+ const now = Date.now();
2826
+ const accessExpiresAt = new Date(now + session.expiresIn * 1e3).toISOString();
2827
+ const sessionExpiresAt = new Date(
2828
+ now + (session.sessionLifetimeDays ?? DEFAULT_SESSION_DAYS) * 24 * 3600 * 1e3
2829
+ ).toISOString();
2830
+ const labels = pairLabels(row2);
2831
+ let isDefault = false;
2832
+ await withRefreshLock(
2833
+ target.name,
2834
+ () => updateConfig((fresh) => {
2835
+ const base = getProfile(fresh, target.name);
2836
+ if (target.refuseExisting && base) fail(5 /* VALIDATION */, `Profile "${target.name}" already exists.`);
2837
+ previous = oauthSessionOf(base);
2838
+ const next = { ...profileDefaults(), ...base, api_url: apiUrl, identity_url: identityUrl };
2839
+ clearOAuth(next);
2840
+ next.api_key = void 0;
2841
+ next.api_token = void 0;
2842
+ next.company_token = void 0;
2843
+ next.auth_kind = "oauth";
2844
+ next.login_method = "browser";
2845
+ next.auth_url = authUrl;
2846
+ next.access_token = session.accessToken;
2847
+ next.access_expires_at = accessExpiresAt;
2848
+ next.refresh_token = session.refreshToken;
2849
+ next.session_expires_at = sessionExpiresAt;
2850
+ next.scope_mode = scopeMode;
2851
+ next.workspace_id = pair?.workspaceId;
2852
+ next.environment_id = pair?.environmentId;
2853
+ next.company = company;
2854
+ next.workspace = labels.workspace;
2855
+ next.environment = labels.environment;
2856
+ if (opts.description !== void 0) next.description = opts.description;
2857
+ fresh.profiles[target.name] = next;
2858
+ isDefault = claimDefault(fresh, target.name);
2859
+ })
2860
+ );
2861
+ stored = {
2862
+ ...summary6,
2863
+ default: isDefault,
2864
+ scope_mode: scopeMode,
2865
+ session_expires_at: sessionExpiresAt,
2866
+ company: company ?? null,
2867
+ workspace: pair ? { id: pair.workspaceId, name: labels.workspace ?? null } : null,
2868
+ environment: pair ? { id: pair.environmentId, name: labels.environment ?? null } : null
2869
+ };
2870
+ if (!pair && me !== void 0) {
2871
+ note(
2872
+ "No default workspace/environment: lists cover every pair you can open; writes need --workspace/--environment (see `engini whoami`)."
2873
+ );
2874
+ }
2875
+ } catch (err) {
2876
+ await revokeSession(newSession);
2877
+ throw err;
2625
2878
  }
2626
- saveConfig(config);
2627
- printOutput({ stored: summary6 });
2879
+ if (previous && previous.refresh_token !== session.refreshToken) await revokePrevious(previous);
2880
+ printOutput({ stored });
2881
+ }
2882
+ function addLoginOptions(cmd) {
2883
+ return cmd.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>", "App base URL to persist; hosts the keys and connections pages (default: the API host with api. -> app.)").option("--description <text>", "A note shown in `engini profile list`").option("--expect-company <name>", "Refuse the login unless it belongs to this company").option("--force", "Overwrite existing credentials without confirming").addOption(new Option("--no-browser", "Browser login: print the sign-in link instead of opening it")).option("--timeout <sec>", `Browser login: seconds to wait for the sign-in (default ${DEFAULT_TIMEOUT_SEC})`).option("--auth-url <url>", "Browser login: the sign-in server (default: the API host with api. -> identity.)").option("--allow-host <host>", "Browser login: trust a sign-in host outside engini.io");
2628
2884
  }
2629
2885
  function registerLogin(program) {
2630
- 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");
2886
+ const cmd = program.command("login").description("Sign a profile in: in the browser (default), or `login key` to paste an API key.").argument("[method]", "`key`: paste an API key (read from stdin when piped); omit it for the browser login");
2887
+ addLoginOptions(cmd);
2888
+ cmd.addHelpText(
2889
+ "after",
2890
+ '\nExamples:\n engini login\n engini login --profile staging --api-url https://api.staging.engini.io\n engini login --profile acme --workspace <ws-id> --environment <env-id>\n engini login --no-browser # print the link (same machine, or ssh -L the port)\n printf %s "$KEY" | engini login key --profile ci'
2891
+ );
2631
2892
  addUniversalOptions(cmd, { mutating: true });
2632
- cmd.action(async (opts, command) => {
2633
- await runCommand(command, opts, true, () => loginBody(opts));
2893
+ cmd.action(async (method, opts, command) => {
2894
+ await runCommand(
2895
+ command,
2896
+ opts,
2897
+ true,
2898
+ () => (
2899
+ // Same target as `logout`: the selected profile, else the stored default.
2900
+ loginBody(method, opts, {
2901
+ name: selectedProfile()?.name ?? loadConfig().default_profile ?? "default"
2902
+ })
2903
+ ),
2904
+ { offline: true }
2905
+ );
2634
2906
  });
2635
2907
  }
2636
2908
 
2637
2909
  // src/logout.ts
2638
- function logoutBody() {
2910
+ function hasLogin(profile) {
2911
+ return Boolean(
2912
+ profile.api_key || profile.api_token || profile.access_token || profile.refresh_token || profile.auth_kind === "oauth"
2913
+ );
2914
+ }
2915
+ function clearLogin(profile) {
2916
+ profile.api_key = void 0;
2917
+ profile.api_token = void 0;
2918
+ profile.company_token = void 0;
2919
+ profile.auth_kind = void 0;
2920
+ profile.login_method = void 0;
2921
+ profile.company = void 0;
2922
+ profile.workspace = void 0;
2923
+ profile.environment = void 0;
2924
+ for (const key of OAUTH_FIELDS) profile[key] = void 0;
2925
+ }
2926
+ async function logoutBody() {
2639
2927
  const config = loadConfig();
2640
- if (!(config.api_key || config.api_token)) {
2641
- printOutput({ logged_out: false, noop: true });
2928
+ const selected = selectedProfile();
2929
+ const name = selected?.name ?? config.default_profile;
2930
+ const profile = name !== void 0 ? getProfile(config, name) : void 0;
2931
+ if (selected && !profile) {
2932
+ fail(4 /* NOT_FOUND */, `Unknown profile "${selected.name}".`, "List profiles with `engini profile list`.");
2933
+ }
2934
+ if (!name || !profile || !hasLogin(profile)) {
2935
+ printOutput({ logged_out: false, noop: true, profile: name ?? null });
2642
2936
  return;
2643
2937
  }
2644
2938
  if (dryRun()) {
2645
- printOutput({ would_logout: true });
2939
+ printOutput({ would_logout: true, profile: name });
2646
2940
  return;
2647
2941
  }
2648
- config.api_key = void 0;
2649
- config.api_token = void 0;
2650
- config.company_token = void 0;
2651
- config.auth_kind = void 0;
2652
- saveConfig(config);
2653
- printOutput({ logged_out: true });
2942
+ const outcome = {};
2943
+ await withRefreshLock(name, async () => {
2944
+ const current = getProfile(loadConfig(), name);
2945
+ if (current?.auth_kind === "oauth" && current.refresh_token) {
2946
+ outcome.revoked = await revokeSession(current);
2947
+ if (!outcome.revoked) {
2948
+ note(
2949
+ `Could not revoke the browser session on the server; it stays valid until ${current.session_expires_at ?? "it expires"}. Cleared it locally.`
2950
+ );
2951
+ }
2952
+ }
2953
+ await updateConfig((fresh) => {
2954
+ const row2 = getProfile(fresh, name);
2955
+ if (row2) clearLogin(row2);
2956
+ });
2957
+ });
2958
+ printOutput({ logged_out: true, profile: name, ...outcome });
2654
2959
  }
2655
2960
  function registerLogout(program) {
2656
- const cmd = program.command("logout").description("Clear the stored credentials.");
2961
+ const cmd = program.command("logout").description("Clear the selected profile's stored credentials.");
2657
2962
  addUniversalOptions(cmd, { mutating: true });
2658
2963
  cmd.action(async (opts, command) => {
2659
- await runCommand(command, opts, true, logoutBody);
2964
+ await runCommand(command, opts, true, logoutBody, { offline: true });
2660
2965
  });
2661
2966
  }
2662
2967
 
2663
2968
  // src/shared/connections.ts
2664
- import { readFileSync as readFileSync2 } from "fs";
2969
+ import { readFileSync } from "fs";
2665
2970
  function collect2(value, previous = []) {
2666
2971
  return [...previous, value];
2667
2972
  }
@@ -2675,10 +2980,10 @@ function splitSlugs(spec) {
2675
2980
  function loadFromFile(spec) {
2676
2981
  let text;
2677
2982
  if (spec === "-") {
2678
- text = readFileSync2(0, "utf8");
2983
+ text = readFileSync(0, "utf8");
2679
2984
  } else if (spec.startsWith("@")) {
2680
2985
  try {
2681
- text = readFileSync2(spec.slice(1), "utf8");
2986
+ text = readFileSync(spec.slice(1), "utf8");
2682
2987
  } catch (err) {
2683
2988
  return fail(2 /* USAGE */, `Cannot read ${spec.slice(1)}: ${err.message}`);
2684
2989
  }
@@ -3299,7 +3604,7 @@ function registerOpaDelete(opa) {
3299
3604
  }
3300
3605
 
3301
3606
  // src/opa/download.ts
3302
- import { createHash } from "crypto";
3607
+ import { createHash as createHash2 } from "crypto";
3303
3608
  import { writeFile } from "fs/promises";
3304
3609
  import { basename } from "path";
3305
3610
  function targetFromManifest(url) {
@@ -3343,7 +3648,7 @@ async function downloadBody(opts) {
3343
3648
  const bytes = new Uint8Array(await response.arrayBuffer());
3344
3649
  let verified;
3345
3650
  if (manifest.sha256) {
3346
- const actual = createHash("sha256").update(bytes).digest("hex");
3651
+ const actual = createHash2("sha256").update(bytes).digest("hex");
3347
3652
  if (actual !== manifest.sha256.toLowerCase()) {
3348
3653
  fail(
3349
3654
  5 /* VALIDATION */,
@@ -3608,34 +3913,38 @@ function registerOpa(program) {
3608
3913
  registerOpaDownload(opa);
3609
3914
  }
3610
3915
 
3611
- // src/tools/call.ts
3612
- import { readFileSync as readFileSync4 } from "fs";
3613
- import {
3614
- AnthropicProvider,
3615
- File,
3616
- OpenAIProvider
3617
- } from "@engini/sdk";
3618
-
3619
3916
  // src/results.ts
3620
- import { randomBytes } from "crypto";
3917
+ import { randomBytes as randomBytes2 } from "crypto";
3621
3918
  import {
3622
- existsSync as existsSync2,
3623
- mkdirSync as mkdirSync2,
3624
- readFileSync as readFileSync3,
3919
+ existsSync,
3920
+ mkdirSync,
3921
+ readFileSync as readFileSync2,
3625
3922
  readdirSync,
3923
+ renameSync,
3626
3924
  rmSync,
3627
3925
  statSync,
3628
- writeFileSync as writeFileSync2
3926
+ writeFileSync
3629
3927
  } from "fs";
3630
- import { homedir as homedir2 } from "os";
3631
- import { join as join2 } from "path";
3928
+ import { homedir } from "os";
3929
+ import { join } from "path";
3632
3930
  var MAX_RESULTS = 20;
3633
3931
  var TTL_SECONDS = 24 * 60 * 60;
3634
3932
  var PREVIEW_BYTES = 512;
3933
+ function resultsRoot() {
3934
+ const base = process.platform === "win32" ? process.env.APPDATA ?? homedir() : process.env.XDG_CACHE_HOME ?? join(homedir(), ".cache");
3935
+ return join(base, "engini", "results");
3936
+ }
3635
3937
  function cacheDir() {
3636
- const base = process.platform === "win32" ? process.env.APPDATA ?? homedir2() : process.env.XDG_CACHE_HOME ?? join2(homedir2(), ".cache");
3637
- return join2(base, "engini", "results");
3938
+ return join(resultsRoot(), sandboxKey());
3939
+ }
3940
+ function moveProfileResults(from, to) {
3941
+ const source = join(resultsRoot(), from);
3942
+ if (existsSync(source)) renameSync(source, join(resultsRoot(), to));
3943
+ }
3944
+ function removeProfileResults(name) {
3945
+ rmSync(join(resultsRoot(), name), { recursive: true, force: true });
3638
3946
  }
3947
+ var HANDLE = /^[hr][0-9a-f]{1,32}$/;
3639
3948
  function serialize(value) {
3640
3949
  return JSON.stringify(value ?? null);
3641
3950
  }
@@ -3643,13 +3952,13 @@ function byteLength(value) {
3643
3952
  return Buffer.byteLength(serialize(value), "utf8");
3644
3953
  }
3645
3954
  function jsonFiles(dir) {
3646
- if (!existsSync2(dir)) return [];
3955
+ if (!existsSync(dir)) return [];
3647
3956
  return readdirSync(dir).filter((name) => name.endsWith(".json"));
3648
3957
  }
3649
3958
  function storeResult(output, historyId) {
3650
- const handle = historyId !== null ? `h${historyId}` : `r${randomBytes(6).toString("hex")}`;
3959
+ const handle = historyId !== null ? `h${historyId}` : `r${randomBytes2(6).toString("hex")}`;
3651
3960
  const dir = cacheDir();
3652
- mkdirSync2(dir, { recursive: true, mode: 448 });
3961
+ mkdirSync(dir, { recursive: true, mode: 448 });
3653
3962
  const dataSize = byteLength(output);
3654
3963
  const payload = {
3655
3964
  output: output ?? null,
@@ -3657,15 +3966,16 @@ function storeResult(output, historyId) {
3657
3966
  data_size: dataSize,
3658
3967
  created: Math.floor(Date.now() / 1e3)
3659
3968
  };
3660
- writeFileSync2(join2(dir, `${handle}.json`), JSON.stringify(payload), { mode: 384 });
3969
+ writeFileSync(join(dir, `${handle}.json`), JSON.stringify(payload), { mode: 384 });
3661
3970
  prune();
3662
3971
  return { handle, dataSize };
3663
3972
  }
3664
3973
  function loadResult(handle) {
3665
- const path = join2(cacheDir(), `${handle}.json`);
3666
- if (!existsSync2(path)) return null;
3974
+ if (!HANDLE.test(handle)) return null;
3975
+ const path = join(cacheDir(), `${handle}.json`);
3976
+ if (!existsSync(path)) return null;
3667
3977
  try {
3668
- const data = JSON.parse(readFileSync3(path, "utf8"));
3978
+ const data = JSON.parse(readFileSync2(path, "utf8"));
3669
3979
  return data && typeof data === "object" ? data : null;
3670
3980
  } catch {
3671
3981
  return null;
@@ -3679,7 +3989,7 @@ function listResults() {
3679
3989
  const handle = name.slice(0, -".json".length);
3680
3990
  let mtimeMs;
3681
3991
  try {
3682
- mtimeMs = statSync(join2(dir, name)).mtimeMs;
3992
+ mtimeMs = statSync(join(dir, name)).mtimeMs;
3683
3993
  } catch {
3684
3994
  continue;
3685
3995
  }
@@ -3701,18 +4011,19 @@ function clearResults() {
3701
4011
  const dir = cacheDir();
3702
4012
  let count = 0;
3703
4013
  for (const name of jsonFiles(dir)) {
3704
- rmSync(join2(dir, name), { force: true });
4014
+ rmSync(join(dir, name), { force: true });
3705
4015
  count += 1;
3706
4016
  }
3707
4017
  return count;
3708
4018
  }
3709
4019
  function prune() {
4020
+ for (const name of jsonFiles(resultsRoot())) rmSync(join(resultsRoot(), name), { force: true });
3710
4021
  const dir = cacheDir();
3711
- if (!existsSync2(dir)) return;
4022
+ if (!existsSync(dir)) return;
3712
4023
  const now = Date.now();
3713
4024
  const entries = [];
3714
4025
  for (const name of jsonFiles(dir)) {
3715
- const path = join2(dir, name);
4026
+ const path = join(dir, name);
3716
4027
  try {
3717
4028
  entries.push({ path, mtime: statSync(path).mtimeMs });
3718
4029
  } catch {
@@ -3849,14 +4160,180 @@ function paginate(value, offset, limit) {
3849
4160
  return limit !== null ? sliced.slice(0, limit) : sliced;
3850
4161
  }
3851
4162
 
4163
+ // src/profile/index.ts
4164
+ function activeName(config) {
4165
+ if (process.env.ENGINI_API_TOKEN) return void 0;
4166
+ const fromEnv = process.env.ENGINI_PROFILE;
4167
+ if (fromEnv && validateProfileName(fromEnv) === null) return fromEnv;
4168
+ return config.default_profile;
4169
+ }
4170
+ function row(name, profile, config) {
4171
+ return {
4172
+ name,
4173
+ default: config.default_profile === name,
4174
+ active: activeName(config) === name,
4175
+ company: profile.company ?? null,
4176
+ workspace: profile.workspace ?? null,
4177
+ environment: profile.environment ?? null,
4178
+ scope_mode: profile.scope_mode ?? null,
4179
+ api_url: profile.api_url,
4180
+ auth_kind: profile.auth_kind ?? null,
4181
+ has_credential: Boolean(profile.api_key || profile.api_token || profile.access_token || profile.refresh_token),
4182
+ login_method: profile.login_method ?? null,
4183
+ session_expires_at: profile.session_expires_at ?? null,
4184
+ description: profile.description ?? null
4185
+ };
4186
+ }
4187
+ function required(value, label) {
4188
+ if (!value) fail(2 /* USAGE */, `Missing required argument '${label}'.`);
4189
+ return value;
4190
+ }
4191
+ function nameOrFail(name) {
4192
+ const problem = validateProfileName(name);
4193
+ if (problem) fail(2 /* USAGE */, problem);
4194
+ return name;
4195
+ }
4196
+ function requireProfile(config, name) {
4197
+ const profile = getProfile(config, name);
4198
+ if (!profile) fail(4 /* NOT_FOUND */, `Unknown profile "${name}".`, "List profiles with `engini profile list`.");
4199
+ return profile;
4200
+ }
4201
+ function listBody8() {
4202
+ const config = loadConfig();
4203
+ printOutput(Object.entries(config.profiles).map(([name, profile]) => row(name, profile, config)));
4204
+ }
4205
+ function showBody(name) {
4206
+ const config = loadConfig();
4207
+ const target = name ?? activeName(config);
4208
+ if (!target) fail(4 /* NOT_FOUND */, "No profile to show.", "Create one with `engini login`.");
4209
+ const profile = requireProfile(config, target);
4210
+ printOutput({
4211
+ ...row(target, profile, config),
4212
+ identity_url: profile.identity_url,
4213
+ auth_url: profile.auth_url ?? null,
4214
+ workspace_id: profile.workspace_id ?? null,
4215
+ environment_id: profile.environment_id ?? null
4216
+ });
4217
+ }
4218
+ async function useBody(name) {
4219
+ requireProfile(loadConfig(), name);
4220
+ if (dryRun()) {
4221
+ printOutput({ would_use: name });
4222
+ return;
4223
+ }
4224
+ await updateConfig((config) => {
4225
+ requireProfile(config, name);
4226
+ config.default_profile = name;
4227
+ });
4228
+ note("Shells that export ENGINI_PROFILE are unaffected; this changes only the default.");
4229
+ printOutput({ default: name });
4230
+ }
4231
+ async function renameBody(from, to) {
4232
+ nameOrFail(to);
4233
+ const config = loadConfig();
4234
+ requireProfile(config, from);
4235
+ if (getProfile(config, to)) fail(5 /* VALIDATION */, `Profile "${to}" already exists.`);
4236
+ if (dryRun()) {
4237
+ printOutput({ would_rename: { from, to } });
4238
+ return;
4239
+ }
4240
+ await updateConfig((fresh) => {
4241
+ const profile = requireProfile(fresh, from);
4242
+ if (getProfile(fresh, to)) fail(5 /* VALIDATION */, `Profile "${to}" already exists.`);
4243
+ fresh.profiles[to] = profile;
4244
+ delete fresh.profiles[from];
4245
+ if (fresh.default_profile === from) fresh.default_profile = to;
4246
+ });
4247
+ moveProfileResults(from, to);
4248
+ printOutput({ renamed: { from, to } });
4249
+ }
4250
+ async function rmBody(name, opts) {
4251
+ const config = loadConfig();
4252
+ requireProfile(config, name);
4253
+ const others = Object.keys(config.profiles).filter((n) => n !== name);
4254
+ if (config.default_profile === name && others.length > 0) {
4255
+ fail(
4256
+ 5 /* VALIDATION */,
4257
+ `"${name}" is the default profile.`,
4258
+ "Pick another default first: `engini profile use <name>`."
4259
+ );
4260
+ }
4261
+ if (dryRun()) {
4262
+ printOutput({ would_remove: name });
4263
+ return;
4264
+ }
4265
+ await confirmOrFail(`Remove profile "${name}" and its stored credentials?`, { force: Boolean(opts.force) });
4266
+ await withRefreshLock(name, async () => {
4267
+ const current = getProfile(loadConfig(), name);
4268
+ if (current?.auth_kind === "oauth" && current.refresh_token && !await revokeSession(current)) {
4269
+ note("Could not revoke the profile's browser session on the server; it ends on its own within 30 days.");
4270
+ }
4271
+ await updateConfig((fresh) => {
4272
+ delete fresh.profiles[name];
4273
+ if (fresh.default_profile === name) fresh.default_profile = void 0;
4274
+ });
4275
+ });
4276
+ removeProfileResults(name);
4277
+ printOutput({ removed: name });
4278
+ }
4279
+ var OFFLINE = { offline: true };
4280
+ function registerProfile(program) {
4281
+ const profile = program.command("profile").description("Manage the named logins in config.toml.");
4282
+ const list = profile.command("list").description("List profiles (never shows a credential).");
4283
+ addUniversalOptions(list, { profile: false });
4284
+ list.action(async (opts, command) => {
4285
+ await runCommand(command, opts, false, listBody8, OFFLINE);
4286
+ });
4287
+ const show = profile.command("show").description("Show one profile (default: the active one).").argument("[name]", "Profile name");
4288
+ addUniversalOptions(show, { profile: false });
4289
+ show.action(async (name, opts, command) => {
4290
+ await runCommand(command, opts, false, () => showBody(name), OFFLINE);
4291
+ });
4292
+ const add = profile.command("add").description("Create a profile (an alias of `engini login --profile <name>` that refuses an existing name).").argument("[name]", "Profile name").argument("[method]", "`key` reads the key from stdin when piped; omit it to be asked");
4293
+ addLoginOptions(add);
4294
+ addUniversalOptions(add, { mutating: true, profile: false });
4295
+ add.action(async (name, method, opts, command) => {
4296
+ await runCommand(
4297
+ command,
4298
+ opts,
4299
+ true,
4300
+ () => loginBody(method, opts, { name: nameOrFail(required(name, "name")), refuseExisting: true }),
4301
+ OFFLINE
4302
+ );
4303
+ });
4304
+ const use = profile.command("use").description("Make a profile the default.").argument("[name]", "Profile name");
4305
+ addUniversalOptions(use, { mutating: true, profile: false });
4306
+ use.action(async (name, opts, command) => {
4307
+ await runCommand(command, opts, true, () => useBody(required(name, "name")), OFFLINE);
4308
+ });
4309
+ const rename = profile.command("rename").description("Rename a profile, keeping its login and stored results.").argument("[old]", "Current name").argument("[new]", "New name");
4310
+ addUniversalOptions(rename, { mutating: true, profile: false });
4311
+ rename.action(
4312
+ async (from, to, opts, command) => {
4313
+ await runCommand(command, opts, true, () => renameBody(required(from, "old"), required(to, "new")), OFFLINE);
4314
+ }
4315
+ );
4316
+ const rm = profile.command("rm").description("Remove a profile and its stored credentials.").argument("[name]", "Profile name").option("--force", "Remove without confirming");
4317
+ addUniversalOptions(rm, { mutating: true, profile: false });
4318
+ rm.action(async (name, opts, command) => {
4319
+ await runCommand(command, opts, true, () => rmBody(required(name, "name"), opts), OFFLINE);
4320
+ });
4321
+ }
4322
+
3852
4323
  // src/tools/call.ts
4324
+ import { readFileSync as readFileSync3 } from "fs";
4325
+ import {
4326
+ AnthropicProvider,
4327
+ File,
4328
+ OpenAIProvider
4329
+ } from "@engini/sdk";
3853
4330
  function loadArgs(spec) {
3854
4331
  let text;
3855
4332
  if (spec === "-") {
3856
- text = readFileSync4(0, "utf8");
4333
+ text = readFileSync3(0, "utf8");
3857
4334
  } else if (spec.startsWith("@")) {
3858
4335
  try {
3859
- text = readFileSync4(spec.slice(1), "utf8");
4336
+ text = readFileSync3(spec.slice(1), "utf8");
3860
4337
  } catch (err) {
3861
4338
  return fail(2 /* USAGE */, `Cannot read ${spec.slice(1)}: ${err.message}`);
3862
4339
  }
@@ -4073,7 +4550,7 @@ function parseLimit2(value) {
4073
4550
  }
4074
4551
  return limit;
4075
4552
  }
4076
- async function listBody8(opts) {
4553
+ async function listBody9(opts) {
4077
4554
  if (opts.application && opts.toolset) {
4078
4555
  fail(2 /* USAGE */, "Pass only one of --application / --toolset.");
4079
4556
  }
@@ -4096,7 +4573,7 @@ function registerToolsList(tools) {
4096
4573
  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");
4097
4574
  addUniversalOptions(cmd);
4098
4575
  cmd.action(async (opts, command) => {
4099
- await runCommand(command, opts, false, () => listBody8(opts));
4576
+ await runCommand(command, opts, false, () => listBody9(opts));
4100
4577
  });
4101
4578
  }
4102
4579
 
@@ -4161,12 +4638,9 @@ function registerToolsResult(tools) {
4161
4638
  const cmd = tools.command("result").description("Drill into a sandboxed tools call result.").argument("[handle]", "Result handle from a prior tools call").option("--select <path>", "Dot-path to extract, e.g. items.email (repeatable)", collectSelect).option("--fields <keys>", "Comma-separated keys to project from object(s)").option("--offset <n>", "Skip N items of a list value").option("--limit <m>", "Return at most M list items").option("--full", "Emit the entire stored payload").option("--list", "List stored result handles").option("--clear", "Delete all stored results");
4162
4639
  addUniversalOptions(cmd);
4163
4640
  cmd.action(async (handle, opts, command) => {
4164
- await runCommand(
4165
- command,
4166
- opts,
4167
- false,
4168
- () => resultBody(handle, opts)
4169
- );
4641
+ await runCommand(command, opts, false, () => resultBody(handle, opts), {
4642
+ offline: true
4643
+ });
4170
4644
  });
4171
4645
  }
4172
4646
 
@@ -4372,7 +4846,7 @@ function registerToolsetsGet(toolsets) {
4372
4846
  }
4373
4847
 
4374
4848
  // src/toolsets/list.ts
4375
- async function listBody9() {
4849
+ async function listBody10() {
4376
4850
  const toolsets = await apiErrors(async () => {
4377
4851
  const client = buildClient();
4378
4852
  return client.toolsets.list();
@@ -4387,7 +4861,7 @@ function registerToolsetsList(toolsets) {
4387
4861
  );
4388
4862
  addUniversalOptions(cmd);
4389
4863
  cmd.action(async (opts, command) => {
4390
- await runCommand(command, opts, false, () => listBody9());
4864
+ await runCommand(command, opts, false, () => listBody10());
4391
4865
  });
4392
4866
  }
4393
4867
 
@@ -4777,11 +5251,11 @@ async function addBody(name, url, opts) {
4777
5251
  );
4778
5252
  printOutput(withSecret(created));
4779
5253
  }
4780
- async function listBody10() {
5254
+ async function listBody11() {
4781
5255
  const destinations = await apiErrors(async () => buildClient().triggers.destinations.list());
4782
5256
  printOutput(destinations.map(summarizeDestination));
4783
5257
  }
4784
- async function showBody(raw) {
5258
+ async function showBody2(raw) {
4785
5259
  const name = parseDestName(raw);
4786
5260
  const destination = await apiErrors(async () => buildClient().triggers.destinations.get(name));
4787
5261
  printOutput(summarizeDestination(destination));
@@ -4797,7 +5271,7 @@ async function enableBody(raw) {
4797
5271
  );
4798
5272
  printOutput(summarizeDestination(destination));
4799
5273
  }
4800
- async function rmBody(raw, opts) {
5274
+ async function rmBody2(raw, opts) {
4801
5275
  const name = parseDestName(raw);
4802
5276
  if (dryRun()) {
4803
5277
  printOutput({ would_delete: name, reassign_to: opts.reassign ?? null });
@@ -4843,13 +5317,13 @@ function registerTriggerDestinations(triggers) {
4843
5317
  list.addHelpText("after", "\nExamples:\n engini triggers destinations list --json");
4844
5318
  addUniversalOptions(list);
4845
5319
  list.action(async (opts, command) => {
4846
- await runCommand(command, opts, false, listBody10);
5320
+ await runCommand(command, opts, false, listBody11);
4847
5321
  });
4848
5322
  const show = destinations.command("show").description("One destination's failure counters and status.").argument("[name]", "Destination name");
4849
5323
  show.addHelpText("after", "\nExamples:\n engini triggers destinations show billing");
4850
5324
  addUniversalOptions(show);
4851
5325
  show.action(async (raw, opts, command) => {
4852
- await runCommand(command, opts, false, () => showBody(raw));
5326
+ await runCommand(command, opts, false, () => showBody2(raw));
4853
5327
  });
4854
5328
  const enable = destinations.command("enable").description("Re-enable an auto-disabled destination and reset its failure counter.").argument("[name]", "Destination name");
4855
5329
  enable.addHelpText("after", "\nExamples:\n engini triggers destinations enable billing");
@@ -4865,7 +5339,7 @@ function registerTriggerDestinations(triggers) {
4865
5339
  addUniversalOptions(rm, { mutating: true });
4866
5340
  rm.action(
4867
5341
  async (raw, opts, command) => {
4868
- await runCommand(command, opts, true, () => rmBody(raw, opts));
5342
+ await runCommand(command, opts, true, () => rmBody2(raw, opts));
4869
5343
  }
4870
5344
  );
4871
5345
  const rotate = destinations.command("rotate-secret").description("Issue a new signing secret, invalidating the current one immediately.").argument("[name]", "Destination name").option("--force", "Rotate without confirming");
@@ -4879,7 +5353,7 @@ function registerTriggerDestinations(triggers) {
4879
5353
  }
4880
5354
 
4881
5355
  // src/triggers/events.ts
4882
- async function listBody11(triggerId, opts) {
5356
+ async function listBody12(triggerId, opts) {
4883
5357
  if (triggerId === void 0 || triggerId === "") fail(2 /* USAGE */, "A trigger_id is required.");
4884
5358
  const top = opts.limit !== void 0 ? Number(opts.limit) : void 0;
4885
5359
  const events = await apiErrors(async () => buildClient().triggers.events.list(triggerId, { top }));
@@ -4908,7 +5382,7 @@ function registerTriggerEvents(triggers) {
4908
5382
  addUniversalOptions(events);
4909
5383
  events.action(
4910
5384
  async (triggerId, opts, command) => {
4911
- await runCommand(command, opts, false, () => listBody11(triggerId, opts));
5385
+ await runCommand(command, opts, false, () => listBody12(triggerId, opts));
4912
5386
  }
4913
5387
  );
4914
5388
  const get = events.command("get").description("One event plus its delivery attempts \u2014 the only place a real delivery state is read.").argument("[event_id]", "Event id (te_\u2026)");
@@ -4945,6 +5419,7 @@ function registerTriggersGet(triggers) {
4945
5419
 
4946
5420
  // src/triggers/listen.ts
4947
5421
  import { createHmac } from "crypto";
5422
+ import { EnginiAuthError as EnginiAuthError3 } from "@engini/sdk";
4948
5423
  function emitEvent(frame) {
4949
5424
  console.log(JSON.stringify(frame));
4950
5425
  }
@@ -4990,6 +5465,16 @@ async function forwardEvent(frame, url, secret, signal) {
4990
5465
  return false;
4991
5466
  }
4992
5467
  }
5468
+ function oauthProfileName() {
5469
+ const active = resolveActive();
5470
+ return active.source !== "env-credential" && active.profile.auth_kind === "oauth" ? active.name : void 0;
5471
+ }
5472
+ function storedSession(name) {
5473
+ const profile = getProfile(loadConfig(), name);
5474
+ const expiresAt = profile?.access_expires_at ? Date.parse(profile.access_expires_at) : Number.NaN;
5475
+ return { token: profile?.access_token, expiresAt: Number.isNaN(expiresAt) ? 0 : expiresAt };
5476
+ }
5477
+ var REAUTH_MARGIN_MS = 10 * 60 * 1e3;
4993
5478
  async function listenBody(opts) {
4994
5479
  const secret = opts.signWith ?? process.env.ENGINI_TRIGGER_SIGNING_SECRET;
4995
5480
  if (opts.forward !== void 0 && !secret) {
@@ -5009,24 +5494,48 @@ async function listenBody(opts) {
5009
5494
  let failed = 0;
5010
5495
  try {
5011
5496
  await apiErrors(async () => {
5012
- const stream = buildClient().triggers.subscribe({
5013
- triggerId: opts.trigger,
5014
- triggerSlug: opts.slug,
5015
- applicationSlug: opts.app,
5016
- since: opts.since,
5017
- autoResume: opts.resume,
5018
- signal: controller.signal
5019
- });
5020
- for await (const frame of stream) {
5021
- if (interrupted) break;
5022
- events += 1;
5023
- emitEvent(frame);
5024
- if (opts.forward !== void 0) {
5025
- const ok = await forwardEvent(frame, opts.forward, secret, controller.signal);
5026
- if (ok) forwarded += 1;
5027
- else failed += 1;
5497
+ const oauthProfile = oauthProfileName();
5498
+ let since = opts.since;
5499
+ let reauthBlockedUntil = 0;
5500
+ for (; ; ) {
5501
+ const usedToken = oauthProfile !== void 0 ? storedSession(oauthProfile).token : void 0;
5502
+ const stream = buildClient().triggers.subscribe({
5503
+ triggerId: opts.trigger,
5504
+ triggerSlug: opts.slug,
5505
+ applicationSlug: opts.app,
5506
+ since,
5507
+ autoResume: opts.resume,
5508
+ signal: controller.signal
5509
+ });
5510
+ try {
5511
+ for await (const frame of stream) {
5512
+ if (interrupted) break;
5513
+ events += 1;
5514
+ if (typeof frame.id === "string") since = frame.id;
5515
+ emitEvent(frame);
5516
+ if (opts.forward !== void 0) {
5517
+ const ok = await forwardEvent(frame, opts.forward, secret, controller.signal);
5518
+ if (ok) forwarded += 1;
5519
+ else failed += 1;
5520
+ }
5521
+ if (interrupted) break;
5522
+ }
5523
+ return;
5524
+ } catch (err) {
5525
+ if (!(err instanceof EnginiAuthError3) || err.errorCode !== void 0 || oauthProfile === void 0 || interrupted) {
5526
+ throw err;
5527
+ }
5528
+ if (Date.now() < reauthBlockedUntil) {
5529
+ fail(
5530
+ 3 /* AUTH */,
5531
+ `Your engini session for profile ${oauthProfile} expired.`,
5532
+ `Run \`engini login --profile ${oauthProfile}\`.`
5533
+ );
5534
+ }
5535
+ progress("Session token expired - refreshing and resuming the stream.");
5536
+ await ensureFreshSession(oauthProfile, { force: true, rejectedAccessToken: usedToken });
5537
+ reauthBlockedUntil = storedSession(oauthProfile).expiresAt - REAUTH_MARGIN_MS;
5028
5538
  }
5029
- if (interrupted) break;
5030
5539
  }
5031
5540
  });
5032
5541
  } finally {
@@ -5055,7 +5564,7 @@ function registerTriggerListen(triggers) {
5055
5564
  }
5056
5565
 
5057
5566
  // src/triggers/list.ts
5058
- async function listBody12(opts) {
5567
+ async function listBody13(opts) {
5059
5568
  const top = opts.top !== void 0 ? Number(opts.top) : void 0;
5060
5569
  const triggers = await apiErrors(
5061
5570
  async () => buildClient().triggers.list({
@@ -5084,7 +5593,7 @@ function registerTriggersList(triggers) {
5084
5593
  );
5085
5594
  addUniversalOptions(list);
5086
5595
  list.action(async (opts, command) => {
5087
- await runCommand(command, opts, false, () => listBody12(opts));
5596
+ await runCommand(command, opts, false, () => listBody13(opts));
5088
5597
  });
5089
5598
  }
5090
5599
 
@@ -5123,7 +5632,7 @@ function registerTriggerDisable(triggers) {
5123
5632
  }
5124
5633
 
5125
5634
  // src/triggers/types.ts
5126
- async function listBody13(opts) {
5635
+ async function listBody14(opts) {
5127
5636
  const types = await apiErrors(
5128
5637
  async () => buildClient().triggers.types.list({
5129
5638
  applicationSlug: opts.app,
@@ -5148,7 +5657,7 @@ function registerTriggerTypes(triggers) {
5148
5657
  );
5149
5658
  addUniversalOptions(types);
5150
5659
  types.action(async (opts, command) => {
5151
- await runCommand(command, opts, false, () => listBody13(opts));
5660
+ await runCommand(command, opts, false, () => listBody14(opts));
5152
5661
  });
5153
5662
  const get = types.command("get").description("One trigger type's config_schema, payload_schema and parameters.").argument("[trigger_slug]", "Trigger type slug").option("--app <slug>", "Disambiguate a slug shared by more than one application");
5154
5663
  get.addHelpText("after", "\nExamples:\n engini triggers types get monday_item_created --json");
@@ -5177,7 +5686,7 @@ function registerTriggers(program) {
5177
5686
  }
5178
5687
 
5179
5688
  // src/shared/input.ts
5180
- import { readFileSync as readFileSync5 } from "fs";
5689
+ import { readFileSync as readFileSync4 } from "fs";
5181
5690
  function parseInt1(raw, what) {
5182
5691
  if (raw === void 0 || raw === "") fail(2 /* USAGE */, `${what} is required.`);
5183
5692
  if (!/^\d+$/.test(raw) || Number(raw) < 1) {
@@ -5202,7 +5711,7 @@ function readJsonObject(file, what) {
5202
5711
  fail(2 /* USAGE */, `Pass the ${what} with --file <path>, or pipe it on stdin.`);
5203
5712
  }
5204
5713
  try {
5205
- text = readFileSync5(file === void 0 || file === "-" ? 0 : file, "utf8");
5714
+ text = readFileSync4(file === void 0 || file === "-" ? 0 : file, "utf8");
5206
5715
  } catch (err) {
5207
5716
  return fail(
5208
5717
  2 /* USAGE */,
@@ -5231,7 +5740,7 @@ function readBodyOption(raw, what = "body") {
5231
5740
  }
5232
5741
  const source = raw === "-" ? 0 : raw.slice(1);
5233
5742
  try {
5234
- return parseJsonObject(readFileSync5(source, "utf8"), what);
5743
+ return parseJsonObject(readFileSync4(source, "utf8"), what);
5235
5744
  } catch (err) {
5236
5745
  if (err instanceof CliError) throw err;
5237
5746
  return fail(
@@ -5254,7 +5763,7 @@ function snakeKeys(value, keep = []) {
5254
5763
  }
5255
5764
 
5256
5765
  // src/executions/index.ts
5257
- async function listBody14(opts) {
5766
+ async function listBody15(opts) {
5258
5767
  const top = parseCount(opts.top, "--top");
5259
5768
  const offset = parseCount(opts.offset, "--offset");
5260
5769
  if (opts.all && (top !== void 0 || opts.cursor !== void 0 || offset !== void 0)) {
@@ -5282,13 +5791,13 @@ async function listBody14(opts) {
5282
5791
  printOutput({ items: snakeKeys(items), next_cursor: null, total_count: items.length });
5283
5792
  return;
5284
5793
  }
5285
- const page = await apiErrors(
5794
+ const page2 = await apiErrors(
5286
5795
  async () => client.executions.listPage({ ...filters, top, cursor: opts.cursor, offset })
5287
5796
  );
5288
5797
  printOutput({
5289
- items: snakeKeys(page.items ?? []),
5290
- next_cursor: page.nextCursor ?? null,
5291
- total_count: page.totalCount ?? null
5798
+ items: snakeKeys(page2.items ?? []),
5799
+ next_cursor: page2.nextCursor ?? null,
5800
+ total_count: page2.totalCount ?? null
5292
5801
  });
5293
5802
  }
5294
5803
  async function getBody12(rawId) {
@@ -5363,7 +5872,7 @@ function registerExecutions(program) {
5363
5872
  );
5364
5873
  addUniversalOptions(list);
5365
5874
  list.action(async (opts, command) => {
5366
- await runCommand(command, opts, false, () => listBody14(opts));
5875
+ await runCommand(command, opts, false, () => listBody15(opts));
5367
5876
  });
5368
5877
  const get = executions.command("get").description("One execution: status, timing, activities run, who started it.").argument("[execution_id]", "Execution id");
5369
5878
  get.addHelpText("after", "\nExamples:\n engini executions get 4567 --json");
@@ -5405,6 +5914,7 @@ function registerExecutions(program) {
5405
5914
  }
5406
5915
 
5407
5916
  // src/workflows/index.ts
5917
+ var PAIR = { needsPair: true };
5408
5918
  var PLAN_HELP = "Plan JSON: --file <path>, --file -, or piped stdin. A bare WorkflowPlan ({name, trigger, steps, \u2026}) \u2014 the same shape `engini workflows plan <id>` prints.";
5409
5919
  function fileOption(cmd) {
5410
5920
  return cmd.option("--file <path>", "Plan JSON file ('-' or omit to read stdin)");
@@ -5467,13 +5977,13 @@ function pagingOptions(opts) {
5467
5977
  }
5468
5978
  return { top, offset };
5469
5979
  }
5470
- async function printList(all, drain, page) {
5980
+ async function printList(all, drain, page2) {
5471
5981
  if (all) {
5472
5982
  const items = await apiErrors(drain);
5473
5983
  printOutput({ items, totalCount: items.length });
5474
5984
  return;
5475
5985
  }
5476
- const p = await apiErrors(page);
5986
+ const p = await apiErrors(page2);
5477
5987
  printOutput({ items: p.items ?? [], totalCount: p.totalCount ?? null, offset: p.offset ?? null, top: p.top ?? null });
5478
5988
  }
5479
5989
  async function resolveFolderId(client, rawName) {
@@ -5528,7 +6038,7 @@ async function listFoldersBody(opts) {
5528
6038
  }
5529
6039
  async function revisionsBody(rawId, opts) {
5530
6040
  const workflowId = parseInt1(rawId, "workflow id");
5531
- const page = await apiErrors(
6041
+ const page2 = await apiErrors(
5532
6042
  async () => buildClient().workflows.revisions(workflowId, {
5533
6043
  createdBy: parseOptId(opts.createdBy, "--created-by"),
5534
6044
  createdAfter: opts.createdAfter,
@@ -5538,7 +6048,7 @@ async function revisionsBody(rawId, opts) {
5538
6048
  offset: parseCount(opts.offset, "--offset")
5539
6049
  })
5540
6050
  );
5541
- printOutput({ items: page.items ?? [], totalCount: page.totalCount ?? null, offset: page.offset ?? null, top: page.top ?? null });
6051
+ printOutput({ items: page2.items ?? [], totalCount: page2.totalCount ?? null, offset: page2.offset ?? null, top: page2.top ?? null });
5542
6052
  }
5543
6053
  async function setEnabledBody(rawId, enabled) {
5544
6054
  const workflowId = parseInt1(rawId, "workflow id");
@@ -5647,7 +6157,7 @@ Note: needs a workspace-scoped API key (403 SCOPE_READ_ONLY otherwise). A workfl
5647
6157
  search.addHelpText("after", "\nExamples:\n engini workflows search 'post message' --app slack --kind action");
5648
6158
  addUniversalOptions(search);
5649
6159
  search.action(async (q, opts, command) => {
5650
- await runCommand(command, opts, false, () => searchBody(q, opts));
6160
+ await runCommand(command, opts, false, () => searchBody(q, opts), PAIR);
5651
6161
  });
5652
6162
  const schema = workflows.command("schema").description("Input/output schema of one catalog entry (the slug from `search`).").argument("[slug]", "Catalog slug, e.g. slack.post_message").option("--connection <id>", "Resolve dynamic fields against this connection").option("--kind <kind>", "action | trigger | block").option("--table <id>", "Table the entry is used on").option("--selected <FIELD=value>", "Pick an object for a picker field; repeatable. Needs --connection", collect4);
5653
6163
  schema.addHelpText(
@@ -5657,7 +6167,7 @@ Note: needs a workspace-scoped API key (403 SCOPE_READ_ONLY otherwise). A workfl
5657
6167
  addUniversalOptions(schema);
5658
6168
  schema.action(
5659
6169
  async (slug, opts, command) => {
5660
- await runCommand(command, opts, false, () => schemaBody(slug, opts));
6170
+ await runCommand(command, opts, false, () => schemaBody(slug, opts), PAIR);
5661
6171
  }
5662
6172
  );
5663
6173
  const options = workflows.command("options").description("Dropdown values ({id, label}) for one field of a catalog entry.").argument("[slug]", "Catalog slug").option("--field <name>", "The field to list values for").option("--connection <id>", "Connection to read the values through").option("--kind <kind>", "action | trigger | block").option("--depends-on <field=value>", "Value of a parent field; repeatable", collect4);
@@ -5668,7 +6178,7 @@ Note: needs a workspace-scoped API key (403 SCOPE_READ_ONLY otherwise). A workfl
5668
6178
  addUniversalOptions(options);
5669
6179
  options.action(
5670
6180
  async (slug, opts, command) => {
5671
- await runCommand(command, opts, false, () => optionsBody(slug, opts));
6181
+ await runCommand(command, opts, false, () => optionsBody(slug, opts), PAIR);
5672
6182
  }
5673
6183
  );
5674
6184
  const tables = workflows.command("tables").description("The caller's tables ({id, name}).");
@@ -5676,7 +6186,7 @@ Note: needs a workspace-scoped API key (403 SCOPE_READ_ONLY otherwise). A workfl
5676
6186
  tables.action(async (opts, command) => {
5677
6187
  await runCommand(command, opts, false, async () => {
5678
6188
  printOutput(await apiErrors(async () => buildClient().workflows.listTables()));
5679
- });
6189
+ }, PAIR);
5680
6190
  });
5681
6191
  const columns = workflows.command("columns").description("A table's columns, as a table automation reads them.").argument("[table_id]", "Table id from `workflows tables`").option("--trigger <slug>", "The automation's Tables trigger slug, e.g. tables.Tableonrecordupdated");
5682
6192
  addUniversalOptions(columns);
@@ -5686,14 +6196,14 @@ Note: needs a workspace-scoped API key (403 SCOPE_READ_ONLY otherwise). A workfl
5686
6196
  printOutput(
5687
6197
  await apiErrors(async () => buildClient().workflows.listTableColumns(tableId, { trigger: opts.trigger }))
5688
6198
  );
5689
- });
6199
+ }, PAIR);
5690
6200
  });
5691
6201
  const connections = workflows.command("connections").description("Connections a plan step may bind to.").option("--app <slug>", "Narrow to one application");
5692
6202
  addUniversalOptions(connections);
5693
6203
  connections.action(async (opts, command) => {
5694
6204
  await runCommand(command, opts, false, async () => {
5695
6205
  printOutput(await apiErrors(async () => buildClient().workflows.listConnections({ app: opts.app })));
5696
- });
6206
+ }, PAIR);
5697
6207
  });
5698
6208
  const compile = workflows.command("compile").description("Dry-run a plan: nothing is written. Prints the compiled workflow with its diagnostics and hasErrors.").option("--base-workflow-id <id>", "Compile the plan as an edit of this saved workflow");
5699
6209
  fileOption(compile);
@@ -5713,7 +6223,7 @@ Note: a plan with errors is printed (hasErrors: true), not failed; create/update
5713
6223
  const baseWorkflowId = parseOptId(opts.baseWorkflowId, "--base-workflow-id");
5714
6224
  const plan2 = readJsonObject(opts.file, "plan");
5715
6225
  printOutput(await apiErrors(async () => buildClient().workflows.compile({ plan: plan2, baseWorkflowId })));
5716
- });
6226
+ }, PAIR);
5717
6227
  }
5718
6228
  );
5719
6229
  const plan = workflows.command("plan").description("A saved workflow read back as a plan (the input to `update`).").argument("[workflow_id]", "Workflow id");
@@ -5723,7 +6233,7 @@ Note: a plan with errors is printed (hasErrors: true), not failed; create/update
5723
6233
  await runCommand(command, opts, false, async () => {
5724
6234
  const workflowId = parseInt1(id, "workflow id");
5725
6235
  printOutput(await apiErrors(async () => buildClient().workflows.getPlan(workflowId)));
5726
- });
6236
+ }, PAIR);
5727
6237
  });
5728
6238
  const create = workflows.command("create").description("Create a workflow from a plan. It is created turned off.").option("--folder-id <id>", "Folder to put the workflow in");
5729
6239
  fileOption(create);
@@ -5733,7 +6243,7 @@ Note: a plan with errors is printed (hasErrors: true), not failed; create/update
5733
6243
  ${PLAN_HELP}
5734
6244
  Examples:
5735
6245
  engini workflows create --file plan.json --folder-id 7
5736
- Note: needs a workspace-scoped API key (SCOPE_REQUIRED otherwise). Run \`compile\` first.`
6246
+ Note: works in one workspace + environment (a key's own, or --workspace/--environment on a browser login). Run \`compile\` first.`
5737
6247
  );
5738
6248
  addUniversalOptions(create, { mutating: true });
5739
6249
  create.action(
@@ -5784,7 +6294,49 @@ Note: a turned-on workflow is refused (WORKFLOW_ACTIVE); turn it off in the desi
5784
6294
  }
5785
6295
 
5786
6296
  // src/whoami.ts
5787
- function summary5(me) {
6297
+ function scopeRow(row2) {
6298
+ return {
6299
+ workspace: { id: row2.workspace.id, name: clean(row2.workspace.name) },
6300
+ environment: { id: row2.environment.id, name: clean(row2.environment.name), type: clean(row2.environment.type) }
6301
+ };
6302
+ }
6303
+ function scopeFields(me, active) {
6304
+ const { pair, source } = resolvePair(active);
6305
+ const rows = flattenScopes(me.accessibleScopes);
6306
+ const isOAuth = active.source !== "env-credential" && active.profile.auth_kind === "oauth";
6307
+ const fields = {
6308
+ scope_mode: isOAuth ? active.profile.scope_mode ?? null : me.userType === "apiuser" ? "key" : null,
6309
+ scope_source: source,
6310
+ accessible_scopes: rows.map(scopeRow)
6311
+ };
6312
+ if (!isOAuth) {
6313
+ if (rows.length === 0 && me.workspace && me.environment) {
6314
+ fields.accessible_scopes = [
6315
+ scopeRow({
6316
+ workspace: { id: me.workspace.id, name: me.workspace.name ?? null },
6317
+ environment: { id: me.environment.id, name: me.environment.name ?? null, type: me.environment.type ?? null }
6318
+ })
6319
+ ];
6320
+ }
6321
+ return fields;
6322
+ }
6323
+ fields.session_expires_at = active.profile.session_expires_at ?? null;
6324
+ const row2 = pair ? findScope(rows, pair) : void 0;
6325
+ if (pair && !row2) {
6326
+ note(
6327
+ `${pair.workspaceId}/${pair.environmentId} (from ${source}) is not a workspace/environment you can open now. Pass --workspace/--environment, or set a new default with \`engini login --workspace <id> --environment <id>\`.`
6328
+ );
6329
+ } else if (!pair) {
6330
+ note(
6331
+ "No default workspace/environment: lists cover every pair you can open; creates land in the account's default workspace, Production (the CLI asks for --workspace/--environment on writes)."
6332
+ );
6333
+ }
6334
+ const picked = row2 ? scopeRow(row2) : void 0;
6335
+ fields.workspace = picked?.workspace ?? null;
6336
+ fields.environment = picked?.environment ?? null;
6337
+ return fields;
6338
+ }
6339
+ function summary5(me, source) {
5788
6340
  const ws = me.workspace;
5789
6341
  const env = me.environment;
5790
6342
  return {
@@ -5794,7 +6346,8 @@ function summary5(me) {
5794
6346
  role: clean(me.role),
5795
6347
  user_type: me.userType,
5796
6348
  workspace: ws ? { id: ws.id, name: clean(ws.name) } : null,
5797
- environment: env ? { id: env.id, name: clean(env.name), type: clean(env.type) } : null
6349
+ environment: env ? { id: env.id, name: clean(env.name), type: clean(env.type) } : null,
6350
+ ...source
5798
6351
  };
5799
6352
  }
5800
6353
  async function whoamiBody() {
@@ -5802,13 +6355,23 @@ async function whoamiBody() {
5802
6355
  const client = buildClient();
5803
6356
  return client.auth.whoami();
5804
6357
  });
5805
- printOutput(summary5(me));
6358
+ const active = resolveActive();
6359
+ printOutput(
6360
+ summary5(me, {
6361
+ ...scopeFields(me, active),
6362
+ profile: active.name ?? null,
6363
+ // `flag` | `env` | `default`, or `none` for an ENGINI_API_TOKEN credential.
6364
+ profile_source: active.source === "env-credential" ? "none" : active.source,
6365
+ credential_source: active.source === "env-credential" ? "env" : "profile"
6366
+ })
6367
+ );
5806
6368
  }
5807
6369
  function registerWhoami(program) {
5808
6370
  const cmd = program.command("whoami").description("Report the authenticated user/company and the key's workspace/environment.");
5809
6371
  cmd.addHelpText("after", `
5810
6372
  Examples:
5811
6373
  engini whoami
6374
+ engini whoami --profile staging
5812
6375
  engini whoami --json | jq -r '.email'
5813
6376
  engini whoami --json | jq -r '.workspace.id // "unscoped"'`);
5814
6377
  addUniversalOptions(cmd);
@@ -5823,6 +6386,7 @@ function buildProgram() {
5823
6386
  program.name("engini").description("Engini CLI.").version(VERSION, "--version", "Print the engini SDK/CLI version and exit").showHelpAfterError();
5824
6387
  registerLogin(program);
5825
6388
  registerLogout(program);
6389
+ registerProfile(program);
5826
6390
  registerWhoami(program);
5827
6391
  registerConnect(program);
5828
6392
  registerTools(program);
@@ -5834,23 +6398,25 @@ function buildProgram() {
5834
6398
  registerTriggers(program);
5835
6399
  registerExecutions(program);
5836
6400
  registerWorkflows(program);
6401
+ program.option("--profile <name>", "Use this profile (same as --profile on a command)");
6402
+ program.enablePositionalOptions();
5837
6403
  installHelp(program);
5838
6404
  return program;
5839
6405
  }
5840
6406
 
5841
6407
  // src/update-notice.ts
5842
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync6, writeFileSync as writeFileSync3 } from "fs";
5843
- import { dirname as dirname2, join as join3 } from "path";
6408
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "fs";
6409
+ import { dirname, join as join2 } from "path";
5844
6410
  var REGISTRY_DIST_TAGS_URL = "https://registry.npmjs.org/-/package/%40engini%2Fcli/dist-tags";
5845
6411
  var CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
5846
6412
  var FETCH_TIMEOUT_MS = 1500;
5847
6413
  var SEMVER_RE = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;
5848
6414
  function defaultCachePath() {
5849
- return join3(dirname2(configPath()), "update-check.json");
6415
+ return join2(dirname(configPath()), "update-check.json");
5850
6416
  }
5851
6417
  function readCache(path) {
5852
6418
  try {
5853
- const data = JSON.parse(readFileSync6(path, "utf8"));
6419
+ const data = JSON.parse(readFileSync5(path, "utf8"));
5854
6420
  if (typeof data.checked_at === "number" && typeof data.channel === "string" && (data.latest_version === null || typeof data.latest_version === "string")) {
5855
6421
  return data;
5856
6422
  }
@@ -5859,8 +6425,8 @@ function readCache(path) {
5859
6425
  return null;
5860
6426
  }
5861
6427
  function writeCache(path, cache) {
5862
- mkdirSync3(dirname2(path), { recursive: true });
5863
- writeFileSync3(path, JSON.stringify(cache));
6428
+ mkdirSync2(dirname(path), { recursive: true });
6429
+ writeFileSync2(path, JSON.stringify(cache));
5864
6430
  }
5865
6431
  async function fetchLatest(fetchImpl, channel) {
5866
6432
  try {